How to vectorize a for-loop?

Hello!
I would appreaciate any help vectorizing the for loop below. The problem i cannot solve is how to take out the constants from wdrive and multiply it with the rest, according to the loop below. I want to become better at vectorizing my MATLAB code so I would really appreciate any help! Thanks alot!
%S and R are square matrices (404*404).
%fc is a column vector
wdrive=0:1:800;
a2=zeros(2*dofs,(length(wdrive)));
b2=zeros(2*dofs,(length(wdrive)));
Amp=zeros(1,length(wdrive));
SRS=S*(R\S);
SRfc=S*(R\fc);
for i=1:length(wdrive)
a2(:,i)=(wdrive(i)^2*SRS+R)\(fs-wdrive(i)*SRfc);
b2(:,i)=(R)\(fc+wdrive(i)*S*a2(:,i));
Amp(i)=sqrt(a2(dofs-1,i)^2+b2(dofs-1,i)^2);
end

2 commentaires

Matt J
Matt J le 18 Mai 2013
What is "fs"?
Samuel Hammarberg
Samuel Hammarberg le 18 Mai 2013
Ops! Forgot to specify that. Fc is a column vector with the same size as Fs.

Connectez-vous pour commenter.

 Réponse acceptée

Matt J
Matt J le 18 Mai 2013
Modifié(e) : Matt J le 18 Mai 2013

0 votes

I don't think you can vectorize everything, but you can cut down on the operations done inside the loop,
Rfc=R\fc;
SRS=S*(R\S);
SRfc=S*(Rfc);
rhs=bsxfun(@minus,fs,SRfc*wdrive);
for i=1:length(wdrive)
a2(:,i)=(wdrive(i)^2*SRS+R)\rhs(:,i);
end
b2=Rfc+R\S*bsxfun(@times, wdrive, a2);
Amp=abs(a2(dofs-1,:)+i*b2(dofs-1,:));

5 commentaires

Samuel Hammarberg
Samuel Hammarberg le 18 Mai 2013
Tank you for answering! I will make sure to try it your way once I get home!
Samuel Hammarberg
Samuel Hammarberg le 18 Mai 2013
Modifié(e) : Matt J le 19 Mai 2013
I have now tried and had to change just one little thing. This is what i ended up with, it's not too pretty but atleast it's faster now.
Rfc=R\fc;
SRS=S*(R\S);
SRfc=S*(Rfc);
rhs=bsxfun(@minus,fs,SRfc*wdrive);
for i=1:length(wdrive)
a2(:,i)=(wdrive(i)^2*SRS+R)\(rhs(:,i));
end
b2=R\(bsxfun(@plus,fc,(bsxfun(@times,wdrive,S*a2))));
Amp=abs(a2(dofs-1,:)+i*b2(dofs-1,:));
Matt J
Matt J le 19 Mai 2013
Samuel Hammarberg commented:
It would still be sweet if you, somehow, could get rid of the for loop altogether. So if some one could crack that, that would be great!
Thank you very much!
Matt J
Matt J le 19 Mai 2013
The for-loop isn't slowing you down significantly. You just have a lot of matrix inversions
(wdrive(i)^2*SRS+R)
to do. There's no simplification to this that I can see, unless there is some special structure in S and R that you haven't mentioned.
Matt J
Matt J le 19 Mai 2013
You could also try parfor, if you have the Parallel Computing Toolbox.

Connectez-vous pour commenter.

Plus de réponses (1)

Samuel Hammarberg
Samuel Hammarberg le 18 Mai 2013
Modifié(e) : Matt J le 19 Mai 2013

0 votes

Relocated to Comment by Matt J

Catégories

En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by