Vectorize this for loop

Hey everyone,
I have identified the following for-loop to be a time-eater in my program and I'm looking to find a more efficient solution, possibly vectorizing the whole thing.
What I have is a tool path that consists of - x,y,z coordinates - o1,o2,o3 which are the orientation vector components - t as the time vector
Now I want to calculate the coodinates of an eccentric movement orthogonal to the orientation with frequency fecc and radius recc to that toolpath. For that I have come up with the following code:
for i=1:length(t)
v=null([o1(:,i) o2(:,i) o3(:,i)]); %Create orthogonal vectors in circle plane
xecc=recc*(sin(fecc*t)*v(1,1)+cos(fecc*t)*v(1,2)); %x of circle in 3D
yecc=recc*(sin(fecc*t)*v(2,1)+cos(fecc*t)*v(2,2)); %y of circle in 3D
zecc=recc*(sin(fecc*t)*v(3,1)+cos(fecc*t)*v(3,2)); %z of circle in 3D
end
This works fine but takes a lot of time (some paths include up to 100k points). Is there any way to vectorize this or increase efficiency by other means?
Thanks in advance!
Michael
I attached an example so you see what this is about. Cyan is x,y,z and Red is x+xecc, y+yecc, z+zecc: http://img836.imageshack.us/img836/750/examplekp.jpg

2 个评论

I assume there is a missing ( in the "xecc=recc*sin(" line.
yeah thanks, I corrected it now

请先登录,再进行评论。

 采纳的回答

did you use
profile on
profile viewer
to ID where the time is lost?
You could pull the
sin(fecc*t)
cos(fecc*t)
outside the loop since you are doing the calculation everytime when the result is always the same (no dependence on t(i).

1 个评论

no just used tic toc to measure the time spent in the loop

请先登录,再进行评论。

更多回答(2 个)

Jan
Jan 2011-5-31
At first start with the standard method to accelerate loops: Move all repeated calculations outside!
s = sin(fecc * t);
c = cos(fecc * t);
for i=1:length(t)
v = null([o1(:,i), o2(:,i), o3(:,i)]);
xecc = recc * (s * v(1,1) + c * v(1,2));
yecc = recc * (s * v(2,1) + c * v(2,2));
zecc = recc * (s * v(3,1) + c * v(3,2));
end
But now I'm confused: the values for xecc, yecc and zecc are overwritten in each iteration. Then the loop is not necessary at all. This makes a further vectorization hard...

1 个评论

i think that was part of the problem because every iteration the whole vector is recalculated

请先登录,再进行评论。

thanks to both of you for the fast replies. I changed the code to
xecc=zeros(1,length(t));
yecc=zeros(1,length(t));
zecc=zeros(1,length(t));
c_sin=recc*sin(fecc*t);
c_cos=recc*cos(fecc*t);
for i=1:length(t)
v=null([o1(:,i) o2(:,i) o3(:,i)]);
xecc(i)=c_sin(i)*v(1,1)+c_cos(i)*v(1,2);
yecc(i)=c_sin(i)*v(2,1)+c_cos(i)*v(2,2);
zecc(i)=c_sin(i)*v(3,1)+c_cos(i)*v(3,2);
end
that took me from Elapsed time is 9.421981 seconds. to Elapsed time is 0.1321981 seconds.
Thanks!!

类别

在 帮助中心 和 File Exchange 中查找有关 Get Started with MATLAB 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by