09.02.2014 Views

MatLab Programming – Lesson 2

MatLab Programming – Lesson 2

MatLab Programming – Lesson 2

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

<strong>MatLab</strong> <strong>Programming</strong> – <strong>Lesson</strong> 2<br />

1) Log into your computer and open <strong>MatLab</strong>…<br />

2) If you don’t have the previous M-scripts saved, you can find them at<br />

http://www.physics.arizona.edu/~physreu/dox/matlab_lesson_1.pdf.<br />

Review 2-D Graphing<br />

Copy the following script into a new M-file.<br />

close all; clear all; clc; format short;<br />

% Its not usually smart to condense lines like above<br />

% (hard to read later), but with the beginning stuff I<br />

% usually do anyway.<br />

x = linspace(0,3,1000);<br />

y_a = x;<br />

y_b = x.^2;<br />

y_c = sin(x);<br />

y_d = exp(x);<br />

y_e = log(x);<br />

plot(x,y_a,x,y_b,x,y_c,x,y_d,x,y_e); % Multiple plots on single graph.<br />

legend('linear','quadratic1','sinusoidal',...<br />

'exponential','logarithmic',2);<br />

% Triple dots allows you to wrap lines (so you can see better).<br />

% Use the help menu to find out what the '2' does for ‘legend’<br />

(search ‘legend’ in the help index).<br />

Now replace the plot command with:<br />

plot(x,y_a,'go', x,y_b,'b.',...<br />

x,y_c,'r-', x,y_d,'k:',...<br />

x,y_e,'p--',...<br />

'markersize',10,'markerfacecolor','y');<br />

¿Practice:<br />

Graph sin(x) in the interval [0,3] and cos(x) in the<br />

interval [-3,0] including a legend. It should look like<br />

the graph on the right. Hint: you should use different<br />

domains in your plot statement.


More 3-D Graphing<br />

A contour plot shows the height of a function. Copy the following script into a new M-file.<br />

close all;clear all;clc;format short;<br />

x = linspace(-2, 2, 30);<br />

y = linspace(-2, 2, 30);<br />

[X,Y] = meshgrid(x,y);<br />

z = (X-1).^2 + Y.^2;<br />

% This is the function of a depression located<br />

% at x=1 and y=0.<br />

contour(X,Y,z,25);<br />

% The 25 colored contour lines show the height<br />

% of z.<br />

xlabel('x'); ylabel('y');<br />

¿Practice:<br />

Use a contour plot to find the min and max of sin(x)*sin(y) in the interval -10 < x < 10, and<br />

-10 < y < 10.


More 3-D Graphing<br />

A surfc plot is in 3-D and shows the contours. Copy the following script into a new M-file.<br />

close all;clear all;clc;format short;<br />

x = linspace(-5, 5, 100);<br />

y = linspace(-5, 5, 100);<br />

[X,Y] = meshgrid(x,y);<br />

z = sin(X).*sin(Y);<br />

surfc(X,Y,z);<br />

colormap copper;<br />

% Colormaps allow you to process the<br />

% color of images to your own specifications.<br />

xlabel('x'); ylabel('y'); zlabel('z');<br />

¿Practice:<br />

Find a cool function for z to make a surfc plot. Dress up the plot with some fancy commands.<br />

Perhaps it will be a picture for your web site!


More 3-D Graphing<br />

‘plot3’ simply graphs x-y-z coordinates (not as useful as you would think). Copy the following<br />

script into a new M-file.<br />

close all;clear all;clc;format short;<br />

x = linspace(1,10*pi,1000);<br />

plot3(sin(x),cos(x),x);<br />

% Plot a 3-D spiral.<br />

grid on;<br />

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


While Loops<br />

A while loop continues until a condition is met. Copy the following script into a new M-file.<br />

close all; clear all; clc; format short;<br />

x = 0;<br />

n_count = 0;<br />

while x < 99,<br />

x = 100*rand(1);<br />

n_count = n_count + 1;<br />

end;<br />

if abs(n_count - 300) < 1e-9,<br />

break;<br />

end;<br />

% Always include an escape for a while loop<br />

% in case you screw up the programming. Otherwise,<br />

% you might get caught in an infinite loop.<br />

if n_count < 300,<br />

disp(['It took ',num2str(n_count),' random tries to beat 99.']);<br />

% Re-run this program several times. What is the largest<br />

% n_count you found? Compare with a neighbor.<br />

else,<br />

disp('Timed out!');<br />

end;<br />

¿Practice:<br />

Write a program that creates takes the natural logarithm of a random number between 1 and 100<br />

until it is larger than 4.6 using a while loop. What is the smallest number of times your random<br />

number has to be generated in any single run of your program?


Exporting Data (SKIP THIS SECTION FOR NOW, GO TO LESSON 3.)<br />

You can create a file to store data by opening, printing and closing. Copy the following script into<br />

a new M-file.<br />

close all; clear all; clc; format short;<br />

outfile = fopen('my_data.txt','wt');<br />

x = 0;<br />

n_count = 0;<br />

while x < 99,<br />

x = 100*rand(1);<br />

n_count = n_count + 1;<br />

fprintf(outfile,'%10d %+6.3f\n',n_count,x);<br />

end;<br />

if abs(n_count - 300) < 1e-9,<br />

break;<br />

end;<br />

% Always include an escape for a while loop<br />

% in case you screw up the programming. Otherwise,<br />

% you might get caught in an infinite loop.<br />

if n_count < 300,<br />

disp(['It took ',num2str(n_count),' random tries to beat 99.']);<br />

% Re-run this program several times. What is the largest<br />

% n_count you found? Compare with a neighbor.<br />

else,<br />

disp('Timed out!');<br />

end;<br />

fclose(outfile);<br />

¿Practice:<br />

Write a program that randomly generates the ages of 100 people between the values of 0 and 110.<br />

Do not give all ages equal weight, but let older ages be less likely. Hint: try taking one minus the<br />

negative exponential of a random number and multiplying the result by 110,<br />

110*(1-exp(-rand(1,100))). Export this to a .txt data file.


Importing Data (SKIP THIS SECTION FOR NOW, GO TO LESSON 3.)<br />

You can open a data file using load. Copy the following script into a new M-file.<br />

close all; clear all; clc; format short;<br />

load my_data.txt;<br />

% Creates array called 'my_data' with<br />

% stored values as elements (super handy).<br />

n_size = size(my_data,1);<br />

% Find out how many rows of data there are.<br />

n_sum = 0;<br />

for i_loop = 1:n_size,<br />

end;<br />

if my_data(i_loop,2) > 50,<br />

n_sum = n_sum + 1;<br />

end;<br />

% This loop counts how many times the random number<br />

% was above 50.<br />

disp([num2str(n_sum),' random number were above 50.']);<br />

¿Practice:<br />

Write a program that reads into memory the data file of random birthdays that you created in the<br />

previous section. Have you program count the number of birthdays above 50. Does the weighting<br />

algorithm you used to generate the data seem realistic?<br />

Note: It took me days to figure out a more complicated importing of data. If you have a giant data set<br />

that is much too large to load into your memory all at once, you can read it in line by line. See my<br />

program http://bohr.physics.arizona.edu/~leone/pj/p_visualize.pdf.


Inline Functions (SKIP THIS SECTION FOR NOW, GO TO LESSON 3.)<br />

Sure <strong>MatLab</strong> knows sin, cos, exp, and several other functions. But you can create your own<br />

functions inside your program to be called later. Later you will learn how to call functions that are entire<br />

separate programs. Copy the following script into a new M-file.<br />

close all;clear all;clc;format short;<br />

% Let's make some variables to use in our functions:<br />

a = 5;<br />

b = 3.5;<br />

% NOW MAKE SOME FUNCTIONS.<br />

myfunction = inline('x + y','x','y');<br />

% Make a function that uses two input variables.<br />

% NOW USE THE FUNCTIONS.<br />

myfunction(a,b)<br />

% Leave ';' off so it prints to screen and you can see it.<br />

¿Practice:<br />

Make a program that asks the user for a radius, uses an inline function to calculate the area, and<br />

then displays the area.


Inline Functions (more) (SKIP THIS SECTION FOR NOW, GO TO LESSON 3.)<br />

Inline functions can be used with scalar data (just single numbers) or with arrays or numbers. Be<br />

sure your inline function uses ‘dotted functions’ where appropriate to operate on arrays element-byelement.<br />

Copy the following script into a new M-file.<br />

close all; clear all; clc; format short;<br />

% Let's make some variables to use in our functions:<br />

a = 5;<br />

b = 3.5;<br />

c = pi^pi;<br />

G = 10*rand(20,3);<br />

D = rand(20,3);<br />

D(:,1) = 2*D(:,1)-1;<br />

D(:,2) = 3*D(:,2);<br />

D(:,3) = 4*D(:,3);<br />

% D(:,1) means take all rows and the first column. It<br />

% is the same as typing D(1:end,1).<br />

% NOW MAKE SOME FUNCTIONS.<br />

f_triggy = inline('(sin(x)*(cos(x)))/log(y)','x','y');<br />

% Make a function that uses two input variables.<br />

f_power = inline('(x.^y)./z','x','y','z');<br />

% Make a weird power function that uses three variables<br />

% that could possibly be arrays with the same dimensions.<br />

% NOW USE THE FUNCTIONS.<br />

% 1) Try f_triggy with numbers.<br />

fprintf('1\n');<br />

f_triggy(a,b)<br />

% Leave ';' off so it prints to screen and you can see it.<br />

fprintf('\n\n\n')<br />

% 2) Try f_power with numbers.<br />

fprintf('2\n');<br />

f_power(a,b,c)<br />

fprintf('\n\n\n')<br />

% 3) Try f_triggy with numbers.<br />

fprintf('3\n');<br />

f_triggy(G,D)<br />

% This function was not set up to multiply arrays<br />

% element-by-element; go back and fix it.<br />

fprintf('\n\n\n')<br />

% 4) Try f_power with numbers.


fprintf('4\n');<br />

f_power(G,D,D) % This function works.<br />

fprintf('\n\n\n')<br />

¿Practice:<br />

a) Make your program have a function that is able to take matrix inputs and perform some math<br />

operations with them element-by-element.<br />

b) Now write a program that creates a data set matrix of real numbers with a size of 10000 X 4<br />

where each element is between -100 and 100 in size. Here is a partial example:<br />

M =<br />

-98.1582 19.4765 -68.8456 3.9074<br />

13.8492 39.9856 72.0272 -57.8941<br />

19.7625 -31.5866 -83.6175 22.5648<br />

7.5571 -36.8443 -93.9813 -30.9987<br />

-76.5710 -34.4167 -20.5149 79.9511<br />

-36.2071 -18.6431 2.2775 -72.2470<br />

-0.0191 -61.5494 32.8980 1.1866<br />

-69.4575 56.4274 -30.9396 -40.2943<br />

35.6457 -1.9173 -18.6166 -92.8042<br />

-47.9353 -16.0275 -93.9745 50.6888<br />

… and so on…<br />

c) Have your program save this data as a text file. Now save this data file to your website and<br />

include a link to it on your web page.<br />

d) Create another program that reads in a data file and adds all the numbers inside together with<br />

the command sum(sum(M)). Go to another participants web site and download their data, then run<br />

your program on their data.<br />

(END OF LESSON 2)

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!