Saturday, 6 July 2013

Plotting Vectors on matlab

Whereas other computer languages, such asFortran, work on numbers  one at a time, an advantage of matlab is that it handles the matrix as a single unit. Let us consider an example that shows why this is useful.
Imagine you want to plot the functiony= sinxforxbetween 0 and 2π. AFortrancode to do this might look like this:
DIMENSION X(100),Y(100)
PI = 4*ATAN(1)
DO 100 I = 1,100
X(I) = 2*PI*I/100
Y(I) = SIN(X(I))
100 CONTINUE
PLOT(X,Y)
Here we assume that we have access to aFortranplotting package in which PLOT(X,Y)makes sense. Inmatlabwe can get our plot by typing:
x = 0:.1:2*pi;
y = sin(x);
plot(x,y)
The first line uses the colon operator to generate a vectorxof numbers running between 0 and 2πwith increment 0.1. The second line calculates the sine of this array of numbers, and calls the resulty. The third line
produces a plot ofyagainstx. Go ahead and produce the plot. You should get a separate window displaying this plot. We have done in three lines of matlabwhat it took us seven lines to do using theFortran
program above.

No comments:

Post a Comment

Blog Archive