Matlab Chapter 2 Introduction to Programming

advertisement
Matlab Chapter 2 Introduction to Programming
Oh, so then what have we been doing so far? In this chapter we'll write scripts. We've already done this,
and functions, … but we'll be more rigorous about it. P. 46, "these topics serve as ain intro to programming,
wihich will be expanded on in Ch. 6" – so what are we doing in between??? My conclusion -- there's no
logical way to proceed linearly. You have to learn a bunch of different things that individually will make no
sense, before the entire concept and enterprising of programming takes structure and makes sense.
It's important to read the text, and study it, and reread it, and understand it. I'm not going to take you by
the hand through it.
2.1 Algorithms. A key point is reductionism. Break the task into finite smaller steps, each one that can be
tested and validated, as independently as possible from the others. How to do that is a key part of the art of
programming. If you've read Zen and the Art of Motorcycle Maintenance, then think of this as Phaedrus'
knife. And if you haven't read it, then you should. Period.
2.2 Scripts. Any code you expect to reuse should be copied and pasted into a script – otherwise it will be
lost.
Reductionism: the first line(s) of a script should be comments describing what the script does or intends
to do, it should include your initials and the date. If its based on notes in a notebook, the name of the
notebook and page number is helpful.
Comments can also include revision history.
Comments vs. self-documenting code: I vastly prefer the latter. Comments easily get out of sync. Self
documenting code can't. So what is self-documenting code?
E.g., area = pi .* radius .^2; % are comments necessary?
2.3 i/o: Want to get more sexy than input? Try >>doc inputdlg. Want to ask for a file? uigetfile(…).
There's a lot of power with one-line commands. fprintf is a monster. If you've done C programming you'll
find it nicely (or not so nicely) familiar. The format string concept is powerful but cryptic. Work through it,
memorize it, so at least when you see things like a field width specifier, e.g., %2.4f, you aren't clueless and
can efficiently find out what it all means.
I don't use input statements that often in scripts, because the point of the script is to automate some
processes. Functions provide a nicer way to do i/o, and their variables have local scope. What does that
mean?
One of the most powerful ways to learn about Matlab programming is to look inside functions. Some
functions are built-in, compiled (for speed), and their .m files are just for the help system. Others seem very
unnecessarily complicated – designed to handle all sorts of exceptions. But you can still muck around them
and discover tricks. Wonder how a function, e.g., median, works, type:
>>which median
C:\Program Files (x86)\MATLAB\R2013a\toolbox\matlab\datafun\median.m
That's in Matlab's toolbox folder, and its an .m file, so we can edit it:
>> edit median (or >> type median which is safer, you can't mess it up).
… and there's the Matlab source code in all its glory. Most of Matlab is written in Matlab (it is generally
true that most of every computer language is written in itself).
2.5 Plot: super powerful function, and plenty complicated to use. Later I'll show you how to manipulate
plot objects through their structured interface (if you're interested now, try >> h = plot(x,y); get(h) – that's
another way to explore and discover what's under the hood.).
In addition to clf, figure, legend, grid, axis(tight) and for images, axis(equal); For multiple plots in a
figure window, subplot(…).
2.6: save and load.
which f
type f
C:\Program Files (x86)\MATLAB\R2013a\toolbox\br_toolbox\f.m
figure(gcf);
>> type is a quick way to view an .m file (or any text file) without the risk of changing it. What does this
script, f.m do (I use it a lot on small displays).
There are more advanced formatted i/o routines, and some specialized and easy to use ones,
planetaryNebula = imread('ngc6543a.jpg');
imagesc(planetaryNebula);
100
200
300
400
500
600
100
200
300
400
500
600
or if you like in one line, imagesc(imread('ngc6543a.jpg')); axis equal; axis off; title('ngc6543a'); …
2.7 User defined functions: again, the best way to learn is to explore. With time, perserverence, you will be
rewarded. I doubt that you're not smart enough to learn without doing the time.
The first line is the formal function declaration:
function [returnVal1, retVal2, …] = functionName(arg1, arg2, …)
The next line is typically a copy of the first preceeded by % -- so it’s a comment, and perhaps with more
meaningful variable names. The next few lines should be comments describing the function's behavior,
arguments, etc. These will be displayed when the user types >> help functionName, up to the first blank or
non-commented line. I tend to leave a blank line, then continue the comments with my initials and date, and
the revision and debugging history.
Note that you have choices for passing and returning multiple arguments. They can be "packaged" in a
single vector (or data structure), or put in a comma-separated list, or as 'variable', value paired arguments
(e.g., plot(x,y,'linewidth',2)). Mixing up the order of arguments is a common gotcha.
Debugging functions is easiest if you first create them as scripts. That way all variables are local to the
workspace. Once you add the function declaration to the script, test again, and it sometimes fails because of
a necessary variable that you failed to realize, and you'll either need to instantiate it locally or add it to the
argument list.
1.
Reflect: What >5 important things did you learn in this chapter?
2.
Pick a problem from p.80, #30-35. Write the function and write a script or notebook that validates
the function. Have you validated enough cases?
3.
Scope and path are two abstract concepts that will help you understand and have power in Matlab,
but may take some serious effort to wrap your brains around if you're new to computing. Look up
what they mean and describe them.
4.
The min(mat, [], dim) function can take the dimension as a 3 rd argument. How could you use the
path to change this behavior, so you could change the behavior to min(mat,[dim]), without a
required null 2nd argument? And make sure >>help min reflects this behavior.
Download