MATLAB LESSON 3:
FOR LOOP:
Like any other language, MATLAB also has a for loop, but its usage range is expanded compare to other languages. The difference that it takes any expression in the control loop. For example, to calculate the 20 first terms of the Fibonacci series:
fib = zeros(30, 1);
fib(1:2) = [2, 3];
for k = 3:30
fib(k) = fib(k
–1) + fib(k – 2);
end
fib
For loops are used best one the current value depends on the previous values, as the above example. Otherwise, : operations are sufficient.
Table = zeros(12);
for Nrow = 1:12
for Ncolumn = 1:12
Table(Nrow, Ncolumn) = Nrow*Ncolumn;
end
end
Table
This
can be easily simplified to:
N
= 1:12;
Table = N’*N
In Exercise 3 of the homework, the for loop cannot be substituted easily, because each column needs to generate its own permutation. randperm only works in one dimension.
Use this as a rule of thumb: If it takes too much work to replace a for loop, leave it there.
MATLAB GRAPHICS:
The plot function has different forms, depending on the input arguments. If y is a vector, plot(y) produces a piecewise linear graph of the elements of y versus the index of the elements of y. If you specify two vectors as arguments, plot(x,y) produces a graph of y versus x.
For example, these statements use the colon operator to create a vector of x values ranging from zero to 2p, compute the sine of these values, and plot the result. (Use ; the end of the operation to block output of the mathematical operations)
x = 0:pi/100:2*pi;
y = sin(x);
plot(x,y)
hold
Now label the axes and add a title. The characters \pi create the symbol p.
xlabel('x = 0:2\pi')
ylabel('Sine of x')
title('Plot of the Sine Function','FontSize',12)
Multiple x-y pair arguments create multiple graphs with a single call to plot. MATLAB automatically cycles through a predefined (but user settable) list of colors to allow discrimination between each set of data. For example, these statements plot three related functions of x, each curve in a separate distinguishable color.
y2 = sin(x-.25);
y3 = sin(x-.5);
plot(x,y,x,y2,x,y3)
The legend command provides an easy way to identify the individual plots.
legend('sin(x)','sin(x-.25)','sin(x-.5)')
It is possible to specify color, line styles, and markers (such as plus signs or circles) when you plot your data using the plot command.
plot(x,y,'color_style_marker')
color_style_marker is a string containing from one to four characters (enclosed in single quotation marks) constructed from a color, a line style, and a marker type:
Color strings are 'c', 'm', 'y', 'r', 'g', 'b', 'w', and 'k'. These correspond to cyan, magenta, yellow, red, green, blue, white, and black.
Linestyle strings are '-' for solid, '--' for dashed, ':' for dotted, '-.' for dash-dot, and 'none' for no line.
The marker types are '+', 'o', '*', and 'x' and the filled marker types 's' for square, 'd' for diamond, '^' for up triangle, 'v' for down triangle, '>' for right triangle, '<' for left triangle, 'p' for pentagram, 'h' for hexagram, and none for no marker.
Close the figure.
If you specify a marker type but not a linestyle, MATLAB draws only the marker. For example, plot(x,y,'ks') plots black squares at each data point, but does not connect the markers with a line.
The statement plot(x,y,'r:+') plots a red dotted line and places plus sign markers at each data point.
You may want to use fewer data points to plot the markers than you use to plot the lines. This example plots the data twice using a different number of points for the dotted line and marker plots.
figure
x1 = 0:pi/100:2*pi;
x2 = 0:pi/10:2*pi;
plot(x1,sin(x1),'r:',x2,sin(x2),'r+')
Graphing functions automatically open a new figure window if there are no figure windows already on the screen. If a figure window exists, MATLAB uses that window for graphics output. If there are multiple figure windows open, MATLAB targets the one that is designated the "current figure" (the last figure used or clicked in).
To make an existing figure window the current figure, you can click the mouse while the pointer is in that window or you can type figure(n) where n is the number in the figure title bar. The results of subsequent graphics commands are displayed in this window.
To open a new figure window and make it the current figure, type figure.
The subplot command enables you to display multiple plots in the same window or print them on the same piece of paper. Typing subplot(m,n,p) partitions the figure window into an m-by-n matrix of small subplots and selects the pth subplot for the current plot. The plots are numbered along first the top row of the figure window, then the second row, and so on. For example, these statements plot data in four different subregions of the figure window.
figure
t = 0:pi/10:2*pi;
[X,Y,Z] = cylinder(4*cos(t));
subplot(2,2,1); mesh(X)
subplot(2,2,2); mesh(Y)
subplot(2,2,3); mesh(Z)
subplot(2,2,4); mesh(X,Y,Z)
The axis command supports a number of options for setting the scaling, orientation, and aspect ratio of plots. You can also set these options interactively.
Setting Axis Limits
By default, MATLAB finds the maxima and minima of the data to choose the axis limits to span this range. The axis command enables you to specify your own limits
axis([xmin xmax ymin ymax]) or for three-dimensional graphs,
axis([xmin xmax ymin ymax zmin zmax])
Use the command axis auto to re-enable MATLAB's automatic limit selection.
Setting Axis Aspect Ratio
axis also enables you to specify a number of predefined modes. For example, axis square makes the x-axes and y-axes the same length.
axis equal makes the individual tick mark increments on the x- and y-axes the same length. TRY:
plot(exp(i*[0:pi/10:2*pi])). It should look like an oval. Now try axis equal to turn the oval into a proper circle.
axis auto normal returns the axis scaling to its default, automatic mode.
Setting Axis Visibility
You can use the axis command to make the axis visible or invisible.
axis on makes the axis visible. This is the default. axis off makes the axis invisible.
Setting Grid Lines
The grid command toggles grid lines on and off. The statement grid on turns the grid lines on and grid off turns them back off again.
Axis Labels and Titles
The xlabel, ylabel, and zlabel commands add x-, y-, and z-axis labels. The title command adds a title at the top of the figure and the text function inserts text anywhere in the figure. A subset of TeX notation produces Greek letters. You can also set these options interactively:
figure
t = -pi:pi/100:pi;
y = sin(t);
plot(t,y)
axis([-pi pi -1 1])
xlabel('-\pi \leq {\itt} \leq \pi')
ylabel('sin(t)')
title('Graph of the sine function')
text(1,-1/3,'{\itNote the odd symmetry.}')
Saving a Figure
To save a figure, select Save from the File menu. To save it using a graphics format, such as TIFF, for use with other applications, select Export from the File menu. You can also save from the command line - use the saveas command, including any options to save the figure in a different format.