MATLAB Answers

Vectorizing a for loop?

1 view (last 30 days)
Christopher
Christopher on 11 Jul 2013
How would I rewrite this code using say repmat to vectorize it and get rid of the for loop? I have been playing with this, but cannot figure it out. All I am doing is solving the ss2 equation while increasing ILAT. Thank you
A1=[0 0 0];
B1=[-5 5 0];
npan2=3
for ILAT=1:npan1+1
ss2=A1+(B1-A1)/(npan2)*((ILAT)-1);
mat(ILAT,:)=ss2
end

Accepted Answer

dpb
dpb on 11 Jul 2013
Edited: dpb on 11 Jul 2013
For your A1, B1 and npan1=2,
>> bsxfun(@times,A1+(B1-A1),[0:npan1]'/npan2)
ans =
0 0 0
-1.6667 1.6667 0
-3.3333 3.3333 0
>>
Agrees w/ your for..end loop
OK, I add the two blanks and took out the ' MATL'...happy, now, Jan? :)
Now if TMW would just fix it so that NO blanks means MATLAB code and two blanks for wordwrap, how much easier life would be...or at least this one little corner of it... :)
  6 Comments
dpb
dpb on 11 Jul 2013
Perhaps there's a better way to write the help that makes it abundantly clear what's meant--I don't know if my confusion has anything to do w/ anybody else's or not but when I see something that says "markup syntax" I expect it to be syntax. If the key phrase is "two leading blanks" then that's what the syntax is; not " MATLAB code" (w/ two leading blanks).
I still say if TMW wants well-formed code they need it to simply default to that format because the casual user and newbie isn't going to (as has been amply demonstrated) take the time/effort to try to clean up after themselves.
Anyway, Jan, glad to have brought some cheer to somebody along the way... :)
I promised TMW in return for the R2012b upgrade that I'd try to support Answers forum some and supply feedback on it as well as on the product. I don't know how much longer my patience is going to hold though as well as the amount of time it's taken because of the interface. I'm pretty sure I'll be back to cs-sm exclusively before long because of the time issue, though.

Sign in to comment.

More Answers (2)

Christopher
Christopher on 11 Jul 2013
Thank you very much sir! I am still trying to understand bsxfun, as I am relatively new to this command.
  2 Comments
Jan
Jan on 11 Jul 2013
@Cristopher: Please do not post comments in the answers section.

Sign in to comment.


Andrei Bobrov
Andrei Bobrov on 11 Jul 2013
out = (0:npan1).'*(A1+(B1-A1)/npan2);

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!