Basic MATLAB Intro III Plotting Here is a short example to carry out: >x=[0:.1:pi] >y1=sin(x); y2=sqrt(x); y3 = sin(x).*sqrt(x) >plot(x,y1); At this point, you should see a graph of sine. (If not, go to the Window menu.) >plot(x,y2); overwrites the sine graph with x. Let s be a little more careful with managing our plots. First, erase what we ve just done with clf: >clf; We ll try to get the sine graph again: >h1=plot(x,y1); In order to overlay plots, we ll write >hold on; >h2=plot(x,y2); >plot(x,y3); Try this again, but with >x=[0 : pi-.1 : 30*pi] >y4=sin(x); >plot(x,y3); This is one of the dangers of line plots you are simply interpolating a list of points with line segments what you get may not resemble the function you inted to plot there is no simple way to avoid this, other than to sample your function densely enough that you don t see the line segments. Axes and formatting Let s add some axis information: >xlabel( x ); ylabel( y ); >leg( sin(x), sqrt(x), sin(x)*sqrt(x) ) You can control the horizontal and vertical dimensions of the graph: >axis([0 30-7 7]) Add a title: >title( Plotting test ) The three curves are too similar, so we can change some of the attributes to the first (which you may recall were labeled as h1 and h2): >set(h1, linewidth,5, color,[0.5 0 0.5], linestyle, -- ); >set(h2, linewidth,3, color,red, linestyle, -. ); 1
Saving plots At this point, we can save the plot as a pdf: >print -dpdf PlotTest.pdf or as an image: >print -dpng PlotTest.png Sub-plots Read about the subplot command and try the following: >clf; >t=[0:0.01:2*pi]; >x1=sin(t); >x2=sin(2*t); >x3=sin(3*t); >x4=sin(4*t); >subplot(2,2,1) >plot(t,x1); >title( sin(t) ) >subplot(2,2,2) >plot(t,x2); >title( sin(2t) ) >subplot(2,2,3) >plot(t,x3); >title( sin(3t) ) >subplot(2,2,4) >plot(t,x4); >title( sin(4t) ) Programming Inline functions You can program simple functions like x 2 sin x at the command line: f = @(x) x 2 sin(x) gives a function that can be evaluated. Be sure to use * when necessary. Matlab won t recognize 2x, but it will 2*x. In this case, you ll note that the function f can take square matrix arguments as well. Is it clear what f does to square matrices? Question: What is sin(x) when x is a matrix? What is 2 x when x is a matrix? 2
Loops You can program a for loop by writing for j = 1:m (Body of loop).m files More complex functions should be stored in your working directory in a.m file. For instance, a function that adds two matrices called myfunction, should be kept in a file called myfunction.m. You could write: function sum = myfunction(v, w) sum = v + w; The word function at the beginning of the file indicates that it s a function. It returns a variable called sum and it takes two arguments v and w. In order to call the function (at the command line, or within another function) we write: >myfunction(a,b) Here is another example: create a file called sinc.m containing the code: function y=sinc(x,a) % %sinc(a*x): to avoid 0 if(nargin<2) a = 1.0; epsilon = 0.000001; if abs(x)<epsilon y=1; else y=sin(a*x)./(a*x); 3
Create a Matlab function that takes 3 parameters, a, b and n that generates an n by n tridiagonal matrix: 1 b 0... 0 a 1 b... 0 A :=......... 0... a 1 b 0... 0 a 1 (Can you make this without using any loops?) Use this function to solve the system Ax = b = 1/2. 1 2... n for n = 10, a = 1/2, Managing variables Saving variables You can save the variable A in a.mat file by typing >save( A ) This stores the variable A in a file called A.mat. You can do the same thing with multiple variables and by naming the variables by typing >save( filename, var1, var2,...) Clearing variables You can clear the variable A by typing > clear( A ) Loading variables You can load the variables you saved by typing >load( filename ) Images Display a matrix as an image >x = peaks(256); >imagesc(x); >colormap(gray) Create and write an image >a=rand(512); creates a 512 512 matrix with random entries between 0 and 1. >imwrite(a, random.png, png ); 4
stores this as a grayscale image. A more complicated image >x=[0:0.004:1]; >y=[0:0.004:1]; >[X,Y]=meshgrid(x,y); This makes a uniform grid >Z1=(((X 0.5). 2 + (Y 0.5). 2) < 0.125); This is a disk! >imwrite(z1, circle.tif, tif ); >Z2=imread( circle.tif ); >Z2=imagesc(Z2); >colormap( Gray ); >axis equal; axis off; >axis([1 251 1 251]) An alternative to using imagesc is imshow. Exercise 10: Let s use the SVD as a naive image compression algorithm. Investigate the svd command. Run [U,S,V] = svd(z2); Observe that Z2 = USV, Rewrite this as a series of rank one matrices: Z2 = N j=1 A j, where each A j is a matrix having the same dimensions as Z2, and corresponding to one singular value. To compress the matrix, try to use the biggest N 0 singular values: N0 j=1 A j, starting with N 0 = 1, 2,... How do the corresponding compressions match up visually? Observe that compressing with N 0 terms means you are actually storing N 0 *(1 +length(u) +length(v)) numbers. You can try this now on a more natural image. To do so, you need to store your image in your Matlab directory. Load it using the imread command. For instance, by running IM = imread( thomas.jpg ) at the command line (if your image file is called thomas.jpg ). You ll notice that if the image is in color, IM is a 3-d array (a matrix of triples), and that the entries are stored as uint8. You can convert to double precision numbers by using the im2double command. You can covert from color format to grayscale by using rgb2gray. 5