Programming in Matlab
Interpreters vs. Compiliers
Matlab source code is interpreted, although there are ways of compiling it, that is beyond us here. “Interpreted” means that Matlab reads your code (instructions) one line at a time.
Note:
Algorithms
Algorithms are a specific set of instructions to solve a problem. So a recipe is an algorithm, directions to the party tonight is an algorithm, and in this general sense an equation is an algorithm such as g=Gm/r^2. So we can determine the acceleration due to gravity g on object by taking the product of the universal gravity constant G and the mass of whatever is causing the acceleration, such as a planet, and dividing by the square of the distance between the planet and the object.
In Excel, you would represent this algorithm in a formula within a cell.
In Matlab you type it pretty much
like that above but you must first give values to G, m and r. In Matlab assigning
a value is done with the “=” symbol, just as with Excel.
Program Structure
A program is a series of algorithms that allow us to do what we want to do.
In Matlab you edit a text file in the editor with a distinct structure and save it. It will have a .m extension and if you have set your path (with the menu command File > Set Path) then you should be able to just type the name of the file and it will execute as a function just like any other in Matlab. Here is the basic structure of a program as follows:
function argout = myfunction(argin)% next you list your commands
argout = 2 + argin;
saving this and running the function would add 2 to whatever you passed in as argin. for example:
>> a=5
a = 5
>> b=myfunction(a)
b = 7
Iterations
If you want to repeat a command over and over you can use a "for" loop. For example:
>> a=[2 5; 3 8; 1 9]
a =
2 5
3 8
1 9
>> b=[1 2]
b =
1 2
>> a + b
??? Error using ==> plus
Matrix dimensions must agree.
>> for i=1:size(a,1)
c(i,:) = a(i,:) + b
end
c =
3 7
c =
3 7
4 10
c =
3 7
4 10
2 11
Conditionals
If you want to do something based on whether something else is true, use an “if” statement. This is similar to the "if" function in Excel. For example:
>> b=[1 2]
b =
1 2
>> if b(1)>1
c=b+1
end
>> if b(2)>1
c=b+1
end
c =
2 3
C. Connors, 2003