Back to the Control Room



Programming

Basic Programming



So, you have decided to write a program that will calculate y=x^2 for a sequence of x's.

Programming in Matlab is actually very simple for someone with a C background. To program, you just write C-code, minus the declarations, pre-processing, memory allocation (done automatically in Matlab), and other distracting extra junk. Thus, in order to obtain the (x,y) pairs mentioned above, you may try something like the following:

for i=1:10 %equivalent to for(i=1; i<=10; i++)
x(i)=i;
y(i)=x(i)^2

Notice that the % sign is used to comment out the remainder of the line. While the for-loop above works much like in C (as do if-else-then statements, and most of the other conditional logic), this approach does not utilize what Matlab is best at - matrix manipulation. It would be much easier to just represent x as a vector or matrix, and perform matrix operations on it to obtain y. This can be accomplished by the following simpler code:

x=1:10; %x is a vector with 10 elements: [1 2 3 4 5 6 7 8 9 10]
y=x.*x; %the dot means element-by element multiplication (dot product)

We can check that y is what we expected by simply typing in "y" in the command window after running the program. The output should resemble
y=[1 4 9 16 25 36 49 64 81 100]

This result can now be plotted.