You are on page 1of 11

MatLab Programming Lesson 2

1) Log into your computer and open MatLab


2) If you dont have the previous M-scripts saved, you can find them at
http://www.physics.arizona.edu/~physreu/dox/matlab_lesson_1.pdf.
Review 2-D Graphing
Copy the following script into a new M-file.
closeall;clearall;clc;formatshort;
%Itsnotusuallysmarttocondenselineslikeabove
%(hardtoreadlater),butwiththebeginningstuffI
%usuallydoanyway.
x=linspace(0,3,1000);
y_a=x;
y_b=x.^2;
y_c=sin(x);
y_d=exp(x);
y_e=log(x);
plot(x,y_a,x,y_b,x,y_c,x,y_d,x,y_e);%Multipleplotsonsinglegraph.
legend('linear','quadratic1','sinusoidal',...
'exponential','logarithmic',2);
%Tripledotsallowsyoutowraplines(soyoucanseebetter).
%Usethehelpmenutofindoutwhatthe'2'doesforlegend(search
legendinthehelpindex).
Now replace the plot command with:
plot(x,y_a,'go',x,y_b,'b.',...
x,y_c,'r',x,y_d,'k:',...
x,y_e,'p',...
'markersize',10,'markerfacecolor','y');
Practice:
Graph sin(x) in the interval [0,3] and cos(x) in the
interval [-3,0] including a legend. It should look like
the graph on the right. Hint: you should use different
domains in your plot statement.

More 3-D Graphing


A contour plot shows the height of a function. Copy the following script into a new M-file.
closeall;clearall;clc;formatshort;

x=linspace(2,2,30);
y=linspace(2,2,30);

[X,Y]=meshgrid(x,y);

z=(X1).^2+Y.^2;
%Thisisthefunctionofadepressionlocated
%atx=1andy=0.

contour(X,Y,z,25);
%The25coloredcontourlinesshowtheheight
%ofz.

xlabel('x');ylabel('y');

Practice:
Use a contour plot to find the min and max of sin(x)*sin(y) in the interval -10 < x < 10, and
-10 < y < 10.

More 3-D Graphing


A surfc plot is in 3-D and shows the contours. Copy the following script into a new M-file.
closeall;clearall;clc;formatshort;

x=linspace(5,5,100);
y=linspace(5,5,100);

[X,Y]=meshgrid(x,y);

z=sin(X).*sin(Y);

surfc(X,Y,z);
colormapcopper;
%Colormapsallowyoutoprocessthe
%colorofimagestoyourownspecifications.
xlabel('x');ylabel('y');zlabel('z');

Practice:
Find a cool function for z to make a surfc plot. Dress up the plot with some fancy commands.
Perhaps it will be a picture for your web site!

More 3-D Graphing


plot3 simply graphs x-y-z coordinates (not as useful as you would think). Copy the following
script into a new M-file.
closeall;clearall;clc;formatshort;

x=linspace(1,10*pi,1000);

plot3(sin(x),cos(x),x);
%Plota3Dspiral.

gridon;
xlabel('x');ylabel('y');zlabel('z');

While Loops
A while loop continues until a condition is met. Copy the following script into a new M-file.
closeall;clearall;clc;formatshort;

x=0;
n_count=0;

whilex<99,
x=100*rand(1);
n_count=n_count+1;

ifabs(n_count300)<1e9,
break;
end;
%Alwaysincludeanescapeforawhileloop
%incaseyouscrewuptheprogramming.Otherwise,
%youmightgetcaughtinaninfiniteloop.

end;

ifn_count<300,
disp(['Ittook',num2str(n_count),'randomtriestobeat99.']);
%Rerunthisprogramseveraltimes.Whatisthelargest
%n_countyoufound?Comparewithaneighbor.
else,
disp('Timedout!');
end;

Practice:
Write a program that creates takes the natural logarithm of a random number between 1 and 100
until it is larger than 4.6 using a while loop. What is the smallest number of times your random
number has to be generated in any single run of your program?

Exporting Data (SKIP THIS SECTION FOR NOW, GO TO LESSON 3.)


You can create a file to store data by opening, printing and closing. Copy the following script into
a new M-file.
closeall;clearall;clc;formatshort;

outfile=fopen('my_data.txt','wt');

x=0;
n_count=0;

whilex<99,
x=100*rand(1);
n_count=n_count+1;
fprintf(outfile,'%10d%+6.3f\n',n_count,x);

ifabs(n_count300)<1e9,
break;
end;
%Alwaysincludeanescapeforawhileloop
%incaseyouscrewuptheprogramming.Otherwise,
%youmightgetcaughtinaninfiniteloop.

end;

ifn_count<300,
disp(['Ittook',num2str(n_count),'randomtriestobeat99.']);
%Rerunthisprogramseveraltimes.Whatisthelargest
%n_countyoufound?Comparewithaneighbor.
else,
disp('Timedout!');
end;

fclose(outfile);

Practice:
Write a program that randomly generates the ages of 100 people between the values of 0 and 110.
Do not give all ages equal weight, but let older ages be less likely. Hint: try taking one minus the
negative exponential of a random number and multiplying the result by 110,
110*(1-exp(-rand(1,100))). Export this to a .txt data file.

Importing Data (SKIP THIS SECTION FOR NOW, GO TO LESSON 3.)


You can open a data file using load. Copy the following script into a new M-file.
closeall;clearall;clc;formatshort;

loadmy_data.txt;
%Createsarraycalled'my_data'with
%storedvaluesaselements(superhandy).

n_size=size(my_data,1);
%Findouthowmanyrowsofdatathereare.

n_sum=0;

fori_loop=1:n_size,

ifmy_data(i_loop,2)>50,
n_sum=n_sum+1;
end;
%Thisloopcountshowmanytimestherandomnumber
%wasabove50.

end;

disp([num2str(n_sum),'randomnumberwereabove50.']);

Practice:
Write a program that reads into memory the data file of random birthdays that you created in the
previous section. Have you program count the number of birthdays above 50. Does the weighting
algorithm you used to generate the data seem realistic?

Note: It took me days to figure out a more complicated importing of data. If you have a giant data set
that is much too large to load into your memory all at once, you can read it in line by line. See my
program http://bohr.physics.arizona.edu/~leone/pj/p_visualize.pdf.

Inline Functions (SKIP THIS SECTION FOR NOW, GO TO LESSON 3.)


Sure MatLab knows sin, cos, exp, and several other functions. But you can
create your own
functions inside your program to be called later. Later you will learn how to call
functions that are entire
separate programs. Copy the following script into a new M-file.
closeall;clearall;clc;formatshort;

%Let'smakesomevariablestouseinourfunctions:
a=5;
b=3.5;

%NOWMAKESOMEFUNCTIONS.
myfunction=inline('x+y','x','y');
%Makeafunctionthatusestwoinputvariables.

%NOWUSETHEFUNCTIONS.
myfunction(a,b)
%Leave';'offsoitprintstoscreenandyoucanseeit.

Practice:
Make a program that asks the user for a radius, uses an inline function to calculate the area, and
then displays the area.

Inline Functions (more) (SKIP THIS SECTION FOR NOW, GO TO LESSON 3.)
Inline functions can be used with scalar data (just single numbers) or with arrays or numbers. Be
sure your inline function uses dotted functions where appropriate to operate on arrays element-byelement. Copy the following script into a new M-file.
closeall;clearall;clc;formatshort;

%Let'smakesomevariablestouseinourfunctions:
a=5;
b=3.5;
c=pi^pi;
G=10*rand(20,3);
D=rand(20,3);
D(:,1)=2*D(:,1)1;
D(:,2)=3*D(:,2);
D(:,3)=4*D(:,3);
%D(:,1)meanstakeallrowsandthefirstcolumn.It
%isthesameastypingD(1:end,1).

%NOWMAKESOMEFUNCTIONS.
f_triggy=inline('(sin(x)*(cos(x)))/log(y)','x','y');
%Makeafunctionthatusestwoinputvariables.

f_power=inline('(x.^y)./z','x','y','z');
%Makeaweirdpowerfunctionthatusesthreevariables
%thatcouldpossiblybearrayswiththesamedimensions.

%NOWUSETHEFUNCTIONS.
%1)Tryf_triggywithnumbers.
fprintf('1\n');
f_triggy(a,b)
%Leave';'offsoitprintstoscreenandyoucanseeit.
fprintf('\n\n\n')

%2)Tryf_powerwithnumbers.
fprintf('2\n');
f_power(a,b,c)
fprintf('\n\n\n')

%3)Tryf_triggywithnumbers.
fprintf('3\n');
f_triggy(G,D)
%Thisfunctionwasnotsetuptomultiplyarrays
%elementbyelement;gobackandfixit.

fprintf('\n\n\n')

%4)Tryf_powerwithnumbers.
fprintf('4\n');
f_power(G,D,D)%Thisfunctionworks.
fprintf('\n\n\n')

Practice:
a) Make your program have a function that is able to take matrix inputs and perform some math
operations with them element-by-element.
b) Now write a program that creates a data set matrix of real numbers with a size of 10000 X 4
where each element is between -100 and 100 in size. Here is a partial example:
M=
-98.1582 19.4765 -68.8456 3.9074
13.8492 39.9856 72.0272 -57.8941
19.7625 -31.5866 -83.6175 22.5648
7.5571 -36.8443 -93.9813 -30.9987
-76.5710 -34.4167 -20.5149 79.9511
-36.2071 -18.6431 2.2775 -72.2470
-0.0191 -61.5494 32.8980 1.1866
-69.4575 56.4274 -30.9396 -40.2943
35.6457 -1.9173 -18.6166 -92.8042
-47.9353 -16.0275 -93.9745 50.6888
and so on
c) Have your program save this data as a text file. Now save this data file to your website and
include a link to it on your web page.
d) Create another program that reads in a data file and adds all the numbers inside together with
the command sum(sum(M)). Go to another participants web site and download their data, then run
your program on their data.

(END OF LESSON 2)

You might also like