Вы находитесь на странице: 1из 5

Intro Programming Using MatLab

Matt Leone, UA Physics, REU

I developed this tutorial to emphasize some essential programming skills. I have written a more
comprehensive self-guided tutorial that also demonstrates more of the graphics (on the REU website).

There are two ways to use MatLab


1. Command line for simple, quick stuff
2. Using “m-file” scripts for real programs

1. Command line is like using a powerful calculator.


a. <<You Try>> Open MatLab (double click on it!)
Type 2 + 2 and press enter.
You should see ans = 4, and you can use MatLab like a calculator with all sorts of other
functions except you sometimes have to look them up in the help menu/index.

b. You can define variables that will last until you clear them.
<<You Try>> Type m = 7 and press enter.
m+2
m
m^2
m = m^2
clear m
This should give you some idea of how m is stored and how it can be used or changed.

c. You can also define variables that are matrices (called 'arrays'). (You may copy and paste.)
<<You Try>> Type A = [7, 8, 9; 10, 11, 12] and press enter.
A(2, 3)
B = [0:2:10]
C = transpose(1:2:11)
dot(B, C)
D = rand(6, 6)
E = linspace(0, 5, 6)
E * E'
E' * E
F = exp(E)
zeros(5, 9)
ones(11, 5)
This shows just a few ways to make and use arrays (matrix variables).

PRACTICE 1: Find the natural logarithm for all the numbers between 0 and 100 using arrays.
Show your answer to a mentor.
d. MatLab has a powerful graphics tool.

<<You Try>> x = linspace(0, 10, 100);


y = sin(x);
plot(x, y);
plot(x, y, 'r-');
z = cos(x);
plot(x, y, 'r--', x, z, 'k.');

There is much more about graphing in the other tutorial, but this will be all you need for
today.

----------------------------------------------------------------------------------------------------------------------------

2. A program is a list of many commands


a. In MatLab, you write programs as text files and save them with a '.m' as the file extension.
It is easiest to write these files with MatLab's built in text editor, but in theory you could
use MSWord or any other editor. Before you begin, create a place to keep your MatLab
programs.

<<You Try>> - Create a folder on your desktop or thumb drive called something like
'MyMatLab' or whatever.
- Now set the MatLab's 'Current Folder' to your newly made folder by
clicking on the ellipses button '…' in the middle of the control toolbar
on the top-middle of screen.
- Create a new m-file by clicking 'File > New > Blank M-File'
- Save this (initially blank) file as 'PracticeScript.m' in your new folder.
Note that MatLab program names being with a letter and end in '.m'.
- Now copy and paste the following text into your m-file:

close all; % Closes any current graphics windows.


clear all; % Deletes any current variables.
% Percent signs denote comments.
x = linspace(-7, 7, 1000);
y = sin(x) ./ x; % This is the famous sinc function.
plot(x,y);

- Press F5 on the keyboard to simultaneously save and run. This will


become your favorite button when programming with MatLab.
b. 'if-then' statements gives you the power of logic!

<<You Try>> - Replace the previous m-file content with the following:

close all;
clear all;
user_input = input('Are you happy? (''1'' for Y, ''2'' for N.) \n');
% If you want to single quote to appear as text, you
% have to type two of them!
if user_input == 1,
disp('Oh brother!');
elseif user_input == 2,
disp('Boo hoo.');
else,
disp('Wrong answer!');
end;
% We would need to do something fancier to prevent errors
% when something other than a number is typed.

- Press F5.
- Replace the previous m-file content with the following:

% Tossing a coin.
close all;
clear all;
clc; % Clears the current screen.
x = 2*rand(1,1); % Random number between 0 and 2.
if x >= 1,
disp('Heads!')
else,
disp('Tails!');
end;

- Press F5.

PRACTICE 2: Write a MatLab program that asks the user for their favorite number and then
insults them if you don't like their choice for some reason. Save this file as 'Practice2.m' in your
MatLab folder. Test it on your neighbor! Then show an REU mentor.
c. Numbered loops are useful when you have a specific number of repetitive commands for the
computer to do.

<<You Try>> - Replace the previous m-file content with the following:

close all;
clear all;
clc;
sum_integers = 0;
for i_loop = 1:100,
sum_integers = sum_integers + i_loop;
end;
disp(['The sum of 1 through 100 is ',num2str(sum_integers)]);
% 'num2str' converts a number to text (string) for printing.

- Press F5.
- Replace the previous m-file content with the following:

% Graphing the sum of integers.


close all;
clear all;
clc;
size = 100;
X = linspace(1, size, size); % Array of integers from 1 to 100.
Results = zeros(1, size); % An array to store the answers.
for iSumLoop = 1:size,
Results(1, iSumLoop) = sum( X(1:iSumLoop) );
end;
disp('The sums in order are:');
disp(' ');
for iSumLoop = 1:size,
disp([num2str(Results(1,iSumLoop))]);
end;

- Press F5.

PRACTICE 3: Write a MatLab program that calculates the first 50 integers of the Fibonacci
sequence. Save this program as 'Practice3.m' in your MatLab folder. Write down the 50th integer
in the Fibonacci sequence here to check with your neighbors and mentor. Note: 1, 1, 2, 3, 5, …

50th Fib = ________________________________


d. Unnumbered loops are useful when you are trying to repeat a procedure until a desired result is
achieved.

<<You Try>> - Replace the previous m-file content with the following:

close all; clear all; clc;


coin = 0;
NumberOfHeads = 0;
NumberOfLoops = 0;
while 1, % '1' means 'true'
NumberOfLoops = NumberOfLoops + 1;
coin = 2*rand(1,1);
if coin >= 1,
NumberOfHeads = NumberOfHeads + 1;
end;
if NumberOfHeads == 100,
break; % Leave the while loop.
end;
if NumberOfLoops > 1e6,
break; % Leave loop after 1 million loops.
end;
% Always include an escape for a while loop
% in case you screw up the programming. Otherwise,
% you might get caught in an infinite loop. Here
% it exits after 1 million loops no matter what.
end;
disp(['The number of tosses to 100 heads was ',...
num2str(NumberOfLoops)]);
% Ellipses allow you to make a command over several lines.
% A compound text string is made by ['string1', 'string2']

- Press F5.

PRACTICE 4: Write a MatLab program that asks the user to guess your favorite number between
1 and 20, and does not stop until they get it. Test it on your neighbor to see anyone is psychic.
Don't forget to berate them for their ineptitude when they guess incorrectly! Save this file as
'Practice4.m' in your MatLab folder.

Вам также может понравиться