Drexel dragonThe Math ForumDonate to the Math Forum



Search All of the Math Forum:

Views expressed in these public forums are not endorsed by Drexel University or The Math Forum.


Math Forum » Discussions » Software » comp.soft-sys.matlab

Topic: vectorization loops
Replies: 3   Last Post: Feb 5, 2013 2:35 PM

Advanced Search

Back to Topic List Back to Topic List Jump to Tree View Jump to Tree View   Messages: [ Previous | Next ]
Steven Lord

Posts: 17,944
Registered: 12/7/04
Re: vectorization loops
Posted: Feb 5, 2013 1:16 PM
  Click to see the message monospaced in plain text Plain Text   Click to reply to this topic Reply



"Christian " <muell.halde@iwu.fraunhofer.de> wrote in message
news:kereqq$rnb$1@newscl01ah.mathworks.com...
> Hello,
> does there exist something like an approach for vectorization loops (2, 3
> or 4 nested loops)?


Be more specific, please. There are many different techniques you can use to
write MATLAB code; loops and vectorization are two such techniques.

> I mean using ndgrid, reshape, repmat, sub2ind, ... or whatever.
> I already have read a lot here in the newsgroup and the MATLAB help. Bruno
> show some very good examples here :) but mostly without some explanation.
> So I still encounter difficulties.
> Example for discussion:
>
> n=3;
> a=rand(n,n);
> for i=1:n
> for j=1:n
> b = b + a(i,j)*a(j,i); % command
> end
> end
> b


So you want to take each element of a, multiply it by its reflection in the
main diagonal, and add up all the resulting values?

eachTerm = a.*a.';
b = sum(eachTerm(:));

The first line performs all the operations a(i, j)*a(j, i) at once using
elementwise multiplication and the nonconjugate transpose (in case a
contains some complex values in your real problem, of which this is a
simplified example.) The second line performs the summation.

--
Steve Lord
slord@mathworks.com
To contact Technical Support use the Contact Us link on
http://www.mathworks.com




Point your RSS reader here for a feed of the latest messages in this topic.

[Privacy Policy] [Terms of Use]

© Drexel University 1994-2014. All Rights Reserved.
The Math Forum is a research and educational enterprise of the Drexel University School of Education.