Matlab tips

From Perceptual Learning Wiki

Jump to: navigation, search

Matlab Tips

To increase your Matlab productivity, it helps to open an edit window side by side with the command window. Then, instead of typing the commands directly on the command line and pressing enter, type the commands into the edit window, highlight the text you want to execute (e.g. by pressing Home, Shift-End), and press F9. The advantage of this scheme is that it is much easier to edit your commands in the editor. You can highlight whole pages of commands and execute them with a single keystroke (F9). At the end of the day, you'll have a nice track of all you've done, uncluttered by mistakes and long printouts (which happen all too often if you tend to forget the closing semicolons).

With practice, one learns to make one's commands reusable. For instance, suppose you want to make a series of plots of particular columns in a matrix, and you have several data sets packed in a cell array. Now, the short-sighted way is to type:

plot(x,data{3}(:,1),'b-',x,data{3}(:,5),'r-');axis([0 100 -1 1]);

Type this instead, highlight it, and execute it via F9:

p=3;D=data{p}(:,1);M=data{p}(:,5);
plot(x,A,'b-',x,M,'r');axis([0 100 -1 1]);

The point is that if you want to generate a second, similar figure now, you don't have to wade into the guts of the plot command to change indices. All indices are up front -- you just copy, paste, and edit to get:

p=4;D=data{p}(:,2);M=data{p}(:,5);
plot(x,A,'b-',x,M,'r');axis([0 100 -1 1]);

Without even noticing it, you'll be incrementally building fancy figures with multiple subplots in the course of your routine work.

for p=3:6;D=data{p}(:,mod(p,2)+1);M=data{p}(:,5);
  subplot(2,2,p-2);plot(x,A,'b-',x,M,'r');axis([0 100 -1 1]);
end

You can also copy key results (the stuff Matlab prints back at you) from the command window and paste it in the edited file, comment it, etc. At the end of the session, you'll have a nice record of your key results and a script to re-created them when you revisit the topic later. Raw command-window logs, by contrast, are not nearly as useful.

The workspace viewer is your friend too (ctrl-3).


See also Help Files, Emacs customization