Skip to Main Content Skip to Search
Login
File Exchange
MATLAB Newsgroup
Link Exchange
  Blogs  
 Contest 
MathWorks.com

Thread Subject: How to be a good Matlab programmer

Subject: How to be a good Matlab programmer

From: Rex

Date: 19 Apr, 2008 23:02:01

Message: 1 of 14

Hello,

I was wondering if any of you could suggest any resources for learning
idioms/tricks of effective Matlab programming. I want to make sure I'm
writing code in proper Matlab style. As a very simple example,
although I am used to writing "for" loops in Python/Ruby/C, I have
learned that in Matlab, vectorizing my code is faster and more
concise. I am sure there are other useful tips for people coming from
different languages. Any resources on this?

Thanks,

Rex

Subject: Re: How to be a good Matlab programmer

From: dpb

Date: 19 Apr, 2008 23:23:44

Message: 2 of 14

Rex wrote:
> Hello,
>
> I was wondering if any of you could suggest any resources for learning
> idioms/tricks of effective Matlab programming. I want to make sure I'm
> writing code in proper Matlab style. As a very simple example,
> although I am used to writing "for" loops in Python/Ruby/C, I have
> learned that in Matlab, vectorizing my code is faster and more
> concise. I am sure there are other useful tips for people coming from
> different languages. Any resources on this?

I assume you've read the section in the online documentation on
"Optimizing Matlab Code" in the m-file programming section?

--

Subject: Re: How to be a good Matlab programmer

From: Rex

Date: 20 Apr, 2008 00:23:06

Message: 3 of 14

On Apr 19, 7:23 pm, dpb <n...@non.net> wrote:
> Rex wrote:
> > Hello,
>
> > I was wondering if any of you could suggest any resources for learning
> > idioms/tricks of effective Matlab programming. I want to make sure I'm
> > writing code in proper Matlab style. As a very simple example,
> > although I am used to writing "for" loops in Python/Ruby/C, I have
> > learned that in Matlab, vectorizing my code is faster and more
> > concise. I am sure there are other useful tips for people coming from
> > different languages. Any resources on this?
>
> I assume you've read the section in the online documentation on
> "Optimizing Matlab Code" in the m-file programming section?
>
> --

Yes, I have; that is the type of resource I am looking for. However, I
want to be clear that I'm not just looking for tips on optimizing the
performance of my code; I also want to learn to write more elegant
and concise code. For example, here's an example of how I used to
write for loops:

dims = [10 18 21 25 40 65];
[a,b] = size(dims);
for i = 1:b,
    dlmwrite(sprintf('matrix%d', dims(b)), ones(dims(b)));
end

A friend recently pointed out that I can refactor it as follows:

dims = [10 18 21 25 40 65];
for i = dims,
    dlmwrite(sprintf('matrix%d', i), ones(i));
end

This might be common sense, but I was so used to the idioms of other
programming languages that I didn't think of refactoring my code this
way.

Rex

Subject: Re: How to be a good Matlab programmer

From: Dave Bell

Date: 20 Apr, 2008 01:38:35

Message: 4 of 14

Rex wrote:
> On Apr 19, 7:23 pm, dpb <n...@non.net> wrote:

>> I assume you've read the section in the online documentation on
>> "Optimizing Matlab Code" in the m-file programming section?
>>
>> --
>
> Yes, I have; that is the type of resource I am looking for. However, I
> want to be clear that I'm not just looking for tips on optimizing the
> performance of my code; I also want to learn to write more elegant
> and concise code.
> Rex

That was a good example of what I encountered as a new Matlab user, as
well. It's an entirely different programming paradigm, and it takes a
while to get used to. (I still program Matlab like C!)

Another issue I ran into was simply searching for help. When I was
trying to speed up a project I was working on, someone suggested using
benchmark before and after changing some code. Not wanting to seem
dumber than I was, I didn't ask how to benchmark my code, I just figure
I'd look it up. Try it - there is no such command. One of the two hits I
got from 'Help benchmark' was an article on training a neural net, the
other was about a Simulink model of a Physics 1 experiment with a cart
and mass. I won't admit to how long it took to find 'bench'!

Dave

Subject: Re: How to be a good Matlab programmer

From: NZTideMan

Date: 20 Apr, 2008 03:41:53

Message: 5 of 14

On Apr 20, 1:38=A0pm, Dave Bell <db...@TheSPAMFREEBells.net> wrote:
> Rex wrote:
> > On Apr 19, 7:23 pm, dpb <n...@non.net> wrote:
> >> I assume you've read the section in the online documentation on
> >> "Optimizing Matlab Code" in the m-file programming section?
>
> >> --
>
> > Yes, I have; that is the type of resource I am looking for. However, I
> > want to be clear that I'm not just looking for tips on optimizing the
> > performance of my code; =A0I also want to learn to write more elegant
> > and concise code.
> > Rex
>
> That was a good example of what I encountered as a new Matlab user, as
> well. It's an entirely different programming paradigm, and it takes a
> while to get used to. (I still program Matlab like C!)
>
> Another issue I ran into was simply searching for help. When I was
> trying to speed up a project I was working on, someone suggested using
> benchmark before and after changing some code. Not wanting to seem
> dumber than I was, I didn't ask how to benchmark my code, I just figure
> I'd look it up. Try it - there is no such command. One of the two hits I
> got from 'Help benchmark' was an article on training a neural net, the
> other was about a Simulink model of a Physics 1 experiment with a cart
> and mass. I won't admit to how long it took to find 'bench'!
>
> Dave

There are some lessons we learn from bitter experience. Like (using
your example):
dims =3D [10 18 21 25 40 65];
for i =3D dims,
    dlmwrite(sprintf('matrix%d', i), ones(i));
end
-
-
y=3Damp.*exp(i*phase);

But now, i=3D65, not sqrt(-1).
Lesson: NEVER use i or j as an index

Even if this were in a textbook somewhere (and it probably is), I
think you must make the mistake in order to learn your folly.

But, IMHO, the best way to learn style is to read CSSM, especially
from posters such as "us". If you read his posts and follow his code
(even if it is irrelevant to you), you will learn lots about style
(and new tricks as well).


Subject: Re: How to be a good Matlab programmer

From: Timo Nieminen

Date: 20 Apr, 2008 04:34:06

Message: 6 of 14

On Sat, 19 Apr 2008, Rex wrote:

> I also want to learn to write more elegant
> and concise code. For example, here's an example of how I used to
> write for loops:
>
> dims = [10 18 21 25 40 65];
> [a,b] = size(dims);
> for i = 1:b,
> dlmwrite(sprintf('matrix%d', dims(b)), ones(dims(b)));
> end
>
> A friend recently pointed out that I can refactor it as follows:
>
> dims = [10 18 21 25 40 65];
> for i = dims,
> dlmwrite(sprintf('matrix%d', i), ones(i));
> end

"Concise" is not always good. "Readable" is always good. If conciseness
reduces readability, then it's bad - longer code that's easier to read,
understand, debug, and maintain is better. Often enough, even slower code
can be better if it's easier to read, debug, and maintain, for example,
if said code occupies less than 1% of the runtime.

Consider the joys of ultra-concise C code ...

While your example above is short enough to not suffer, if "dims = ..."
was a long way from the loop, and the loop was longer, the reader might
well assume that "i" is an integer loop counter when reading the code.
Apart from using i or j as counters being bad practice in matlab
(sqrt(-1) and all that), "for dim = dims" is better for readability.

Possible tips for matlab programmers coming from other languages:

(a) Matrix operations are simple and readable. Much more so than loops.

(b) You don't need to declare variables. Thus, beware of mistyped (or
easily mistypeable) variable names - you won't have a compiler telling you
it doesn't know what the new variable is.

(c) When performing calculations using a formula from some source, stick
to the original notation as far as reasonably possible. For example, have
a variable "tau" rather than "OpticalDepth". Some might disagree with
this, given that "OpticalDepth" is more descriptive than "tau", but
assuming you and other readers of the code are familiar with the field,
having matlab code that looks like the formulae in the textbooks is easier
to read IMHO.

(d) As above, don't use i or j as counters.

(e) Functions can return more than one value, e.g., [a,b,c] = foo(d,e).

(f) You can check how many output values are asked for when a function is
called (and, of course, how many input values are passed to the function).

(g) When you write a function, include the text that will be displayed
when the user types "help foo". Make this text useful.

(h) Matlab is nice for debugging. If running scripts, you have access to
all of the variables in memory if it crashes. What about functions? One
approach is to start with it as a script, and then turn it into a
function. Or, use "keyboard" to interrupt execution and give you access to
the function's memory workspace. Also use "keyboard" to interrupt a script
at a particular point.

(i) "whos" is a useful debugging tool.

(j) The profiler ("help profile") can be very useful to help you decide
what parts of your code are worth trying to optmise.

(k) It's easy to use external programs or OS commands ("help system").

(l) While Matlab has functions like "strcat", it can be easier to read,
and more concise, to write things like "a = [ foo bar 'and more text' ];".
This doesn't behave the same as strcat in general, but in the most common
cases, it will.

(m) While you can edit graphs etc using the GUI figure editor (e.g.,
changing line styles and colours, line thicknesses, font sizes, etc.), you
can do this kind of thing via the command line. If you need to do it more
than once, and especially when you need to do it the same way more than
once, a few lines of code (in a function, or easily copy-and-pasted) can
make this easy compared to remembering what you did last time (possibly
months ago).

(o) Graphs can also be good debugging tools.

--
Timo, who has written much bad Matlab code

Subject: Re: How to be a good Matlab programmer

From: Tim Davis

Date: 20 Apr, 2008 09:18:04

Message: 7 of 14

Timo Nieminen <timo@physics.uq.edu.au> wrote in message
...

> While your example above is short enough to not suffer, if
"dims = ..."
> was a long way from the loop, and the loop was longer, the
reader might
> well assume that "i" is an integer loop counter when
reading the code.
> Apart from using i or j as counters being bad practice in
matlab
> (sqrt(-1) and all that), "for dim = dims" is better for
readability.

I have to disagree about the use of i and j. One should
never rely on i or j as the imaginary unit value, since they
can be masked by variables. Use 1i instead, which can never
be overwritten by a variable. It is always a constant equal
to sqrt(-1). The variables i and j are not always equal to
sqrt(-1) and should thus not be relied upon.

The variables i and j have been used since time immemorial
as matrix row and column indices. Stick with standard
mathematical notation and use them as such.

I personally think that the choice made, a long while back,
to use "i" as sqrt(-1) was a mistake.


Subject: Re: How to be a good Matlab programmer

From: dpb

Date: 20 Apr, 2008 14:12:29

Message: 8 of 14

Tim Davis wrote:
...
> The variables i and j have been used since time immemorial
> as matrix row and column indices. Stick with standard
> mathematical notation and use them as such.
>
> I personally think that the choice made, a long while back,
> to use "i" as sqrt(-1) was a mistake.

But 'i' (and 'j') have been used since time immemorial as as sqrt(-1) so
TMW simply stuck w/ standard mathematical notation. :)

--

Subject: Re: How to be a good Matlab programmer

From: dpb

Date: 20 Apr, 2008 14:25:00

Message: 9 of 14

Dave Bell wrote:
> Rex wrote:
...
>> want to be clear that I'm not just looking for tips on optimizing the
>> performance of my code; I also want to learn to write more elegant
>> and concise code.
...
> Another issue I ran into was simply searching for help. When I was
> trying to speed up a project I was working on, someone suggested using
> benchmark before and after changing some code. Not wanting to seem
> dumber than I was, I didn't ask how to benchmark my code, I just figure
> I'd look it up. Try it - there is no such command. One of the two hits I
> got from 'Help benchmark' was an article on training a neural net, the
> other was about a Simulink model of a Physics 1 experiment with a cart
> and mass. I won't admit to how long it took to find 'bench'!

doc lookfor

and, of course, now one can also search the help files that wasn't
particularly feasible in the early days

I think as someone else noted simply reading code and following c.s-s.m
and more importantly, practice are the keys. Matlab is a rich language
and consequently requires effort and time to gain proficiency.

Maybe somebody will jump in during the next work week and can comment on
their favorite texts that might be beneficial in the vein of the thread.
  W/ dialup I don't use the TMW web site nearly enough to be up on what
is there but I'd be surprised if aren't archives of the tutorial and
other resources there as well. Steve Lord can probably stick in a few
pointers there as well as others...

--


--

Subject: Re: How to be a good Matlab programmer

From: Duane Hanselman

Date: 20 Apr, 2008 19:50:03

Message: 10 of 14

Rex <rex.eastbourne@gmail.com> wrote in message
<d6f9728b-07d7-4ebc-8264-e2485cde6259@c65g2000hsa.googlegroups.com>...
> Hello,
>
> I was wondering if any of you could suggest any resources
for learning
> idioms/tricks of effective Matlab programming. I want to
make sure I'm
> writing code in proper Matlab style. As a very simple example,
> although I am used to writing "for" loops in
Python/Ruby/C, I have
> learned that in Matlab, vectorizing my code is faster and more
> concise. I am sure there are other useful tips for people
coming from
> different languages. Any resources on this?
>
> Thanks,
>
> Rex


How about a book, cowritten by a 25 year user of MATLAB?
Mastering MATLAB 7. It covers MATLAB programming, especially
the chapter entitled Examples, Examples, Examples.

I used "classic" MATLAB in 1983 and purchased PC MATLAB in
1985 from the company owner's California garage. (Isn't that
where all California companies get their start?).

Duane

Subject: Re: How to be a good Matlab programmer

From: Timo Nieminen

Date: 20 Apr, 2008 22:09:03

Message: 11 of 14

On Sun, 20 Apr 2008, Tim Davis wrote:

> Timo Nieminen <timo@physics.uq.edu.au> wrote in message
> ...
>
> > While your example above is short enough to not suffer, if
> "dims = ..."
> > was a long way from the loop, and the loop was longer, the
> reader might
> > well assume that "i" is an integer loop counter when
> reading the code.
> > Apart from using i or j as counters being bad practice in
> matlab
> > (sqrt(-1) and all that), "for dim = dims" is better for
> readability.
>
> I have to disagree about the use of i and j. One should
> never rely on i or j as the imaginary unit value, since they
> can be masked by variables. Use 1i instead, which can never
> be overwritten by a variable. It is always a constant equal
> to sqrt(-1). The variables i and j are not always equal to
> sqrt(-1) and should thus not be relied upon.

Excellent advice for robust programming. Especially for scripts.

> The variables i and j have been used since time immemorial
> as matrix row and column indices. Stick with standard
> mathematical notation and use them as such.
>
> I personally think that the choice made, a long while back,
> to use "i" as sqrt(-1) was a mistake.

Perhaps, but now we must live with it.

--
Timo Nieminen - Home page: http://www.physics.uq.edu.au/people/nieminen/
E-prints: http://eprint.uq.edu.au/view/person/Nieminen,_Timo_A..html
Shrine to Spirits: http://www.users.bigpond.com/timo_nieminen/spirits.html

Subject: Re: How to be a good Matlab programmer

From: Tim Davis

Date: 21 Apr, 2008 00:32:02

Message: 12 of 14

Timo Nieminen <timo@physics.uq.edu.au> wrote in message
<Pine.LNX.4.50.0804210807080.8195-100000@localhost>...
> On Sun, 20 Apr 2008, Tim Davis wrote:
>
> > Timo Nieminen <timo@physics.uq.edu.au> wrote in message
> > ...
> >
> > > While your example above is short enough to not suffer, if
> > "dims = ..."
> > > was a long way from the loop, and the loop was longer, the
> > reader might
> > > well assume that "i" is an integer loop counter when
> > reading the code.
> > > Apart from using i or j as counters being bad practice in
> > matlab
> > > (sqrt(-1) and all that), "for dim = dims" is better for
> > readability.
> >
> > I have to disagree about the use of i and j. One should
> > never rely on i or j as the imaginary unit value, since they
> > can be masked by variables. Use 1i instead, which can never
> > be overwritten by a variable. It is always a constant equal
> > to sqrt(-1). The variables i and j are not always equal to
> > sqrt(-1) and should thus not be relied upon.
>
> Excellent advice for robust programming. Especially for
scripts.
>
> > The variables i and j have been used since time immemorial
> > as matrix row and column indices. Stick with standard
> > mathematical notation and use them as such.
> >
> > I personally think that the choice made, a long while back,
> > to use "i" as sqrt(-1) was a mistake.
>
> Perhaps, but now we must live with it.
>
> --
> Timo Nieminen - Home page:
http://www.physics.uq.edu.au/people/nieminen/
> E-prints:
http://eprint.uq.edu.au/view/person/Nieminen,_Timo_A..html
> Shrine to Spirits:
http://www.users.bigpond.com/timo_nieminen/spirits.html

Very true.

Please don't get me wrong, bye the way ... In spite of my
comment you make some excellent points in your post. This
"what is i"? question is a philosophical one and reasonable
points about good coding practice can be made on both sides.

Subject: Re: How to be a good Matlab programmer

From: Steven Lord

Date: 21 Apr, 2008 02:40:11

Message: 13 of 14


"Dave Bell" <dbell@TheSPAMFREEBells.net> wrote in message
news:u8xOj.1371$26.1046@newssvr23.news.prodigy.net...
> Rex wrote:
>> On Apr 19, 7:23 pm, dpb <n...@non.net> wrote:
>
>>> I assume you've read the section in the online documentation on
>>> "Optimizing Matlab Code" in the m-file programming section?
>>>
>>> --
>>
>> Yes, I have; that is the type of resource I am looking for. However, I
>> want to be clear that I'm not just looking for tips on optimizing the
>> performance of my code; I also want to learn to write more elegant
>> and concise code.
>> Rex
>
> That was a good example of what I encountered as a new Matlab user, as
> well. It's an entirely different programming paradigm, and it takes a
> while to get used to. (I still program Matlab like C!)
>
> Another issue I ran into was simply searching for help. When I was trying
> to speed up a project I was working on, someone suggested using benchmark
> before and after changing some code. Not wanting to seem dumber than I
> was, I didn't ask how to benchmark my code, I just figure I'd look it up.
> Try it - there is no such command. One of the two hits I got from 'Help
> benchmark' was an article on training a neural net, the other was about a
> Simulink model of a Physics 1 experiment with a cart and mass. I won't
> admit to how long it took to find 'bench'!

Actually, I think what you want is the Profiler:

http://www.mathworks.com/access/helpdesk/help/techdoc/matlab_env/f9-17018.html

http://www.mathworks.com/access/helpdesk/help/techdoc/ref/profile.html

If you encounter a situation like this in the future, where searching the
documentation or the website using your keyworks doesn't find the
information you want, please let our documentation staff know what you
searched for and what you expected to find with those keywords. On most if
not all of the documentation pages on the website, there's a link in the
upper-right corner of the frame showing the doc page that allows you to
provide feedback. This will let our documentation staff make it easier to
find that information.

--
Steve Lord
slord@mathworks.com


Subject: Re: How to be a good Matlab programmer

From: Rex

Date: 21 Apr, 2008 15:20:08

Message: 14 of 14

On Apr 20, 10:40 pm, "Steven Lord" <sl...@mathworks.com> wrote:
> "Dave Bell" <db...@TheSPAMFREEBells.net> wrote in message
>
> news:u8xOj.1371$26.1046@newssvr23.news.prodigy.net...
>
>
>
> > Rex wrote:
> >> On Apr 19, 7:23 pm, dpb <n...@non.net> wrote:
>
> >>> I assume you've read the section in the online documentation on
> >>> "Optimizing Matlab Code" in the m-file programming section?
>
> >>> --
>
> >> Yes, I have; that is the type of resource I am looking for. However, I
> >> want to be clear that I'm not just looking for tips on optimizing the
> >> performance of my code; I also want to learn to write more elegant
> >> and concise code.
> >> Rex
>
> > That was a good example of what I encountered as a new Matlab user, as
> > well. It's an entirely different programming paradigm, and it takes a
> > while to get used to. (I still program Matlab like C!)
>
> > Another issue I ran into was simply searching for help. When I was trying
> > to speed up a project I was working on, someone suggested using benchmark
> > before and after changing some code. Not wanting to seem dumber than I
> > was, I didn't ask how to benchmark my code, I just figure I'd look it up.
> > Try it - there is no such command. One of the two hits I got from 'Help
> > benchmark' was an article on training a neural net, the other was about a
> > Simulink model of a Physics 1 experiment with a cart and mass. I won't
> > admit to how long it took to find 'bench'!
>
> Actually, I think what you want is the Profiler:
>
> http://www.mathworks.com/access/helpdesk/help/techdoc/matlab_env/f9-1...
>
> http://www.mathworks.com/access/helpdesk/help/techdoc/ref/profile.html
>
> If you encounter a situation like this in the future, where searching the
> documentation or the website using your keyworks doesn't find the
> information you want, please let our documentation staff know what you
> searched for and what you expected to find with those keywords. On most if
> not all of the documentation pages on the website, there's a link in the
> upper-right corner of the frame showing the doc page that allows you to
> provide feedback. This will let our documentation staff make it easier to
> find that information.
>
> --
> Steve Lord
> sl...@mathworks.com

Thanks for the replies, everyone! Those were really helpful and useful.

Tags for this Thread

Add a New Tag:

Separated by commas
Ex.: root locus, bode

What are tags?

A tag is like a keyword or category label associated with each thread. Tags make it easier for you to find threads of interest.

Anyone can tag a thread. Tags are public and visible to everyone.

rssFeed for this Thread

envelope graphic E-mail this page to a colleague

Public Submission Policy
NOTICE: Any content you submit to MATLAB Central, including personal information, is not subject to the protections which may be afforded information collected under other sections of The MathWorks, Inc. Web site. You are entirely responsible for all content that you upload, post, e-mail, transmit or otherwise make available via MATLAB Central. The MathWorks does not control the content posted by visitors to MATLAB Central and, does not guarantee the accuracy, integrity, or quality of such content. Under no circumstances will The MathWorks be liable in any way for any content not authored by The MathWorks, or any loss or damage of any kind incurred as a result of the use of any content posted, e-mailed, transmitted or otherwise made available via MATLAB Central. Read the complete Disclaimer prior to use.
Related Topics