Professional Documents
Culture Documents
Matlab Slides II
Matlab Slides II
Both scripts and functions are saved as .m files. You should make
sure that the .m file is in your working directory (or working path),
otherwise Matlab can’t find it.
Our first script
The outer loop runs across each row, and the inner loop runs down
each column. This allows us to add up every matrix element.
For loops
The first increments over 1, 1.25, 1.5, ... 4. The second loops over
the elements of the vector.
While loops
While loops combine a loop structure with a conditional. The
syntax is as follows:
While loops
This is all we’ll say about flow control, but there are other options,
including switch, break, and return. Feel free to explore these if
you are interested.
Some final notes on scripts
Using flow control lets you write much more sophisticated scripts.
You can run a script from the command window by typing its
name (without the .mat).
Well-written code is properly indented. Matlab generally does
this for you, by adding an indentation every time you start a new
loop or conditional. This helps you keep track of what is going on.
The problem with scripts is that if we want to change something,
we have to load the script, make the adjustment, and run it all
again. If only there was a way we could change values on the go...
Creating functions
To use this function, you would type the following line in a script
or the command window:
[X, ∼] = geometricmean(A, B)