Vectorize this for loop
1 view (last 30 days)
Show older comments
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 Comments
Accepted Answer
Robert Cumming
on 31 May 2011
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).
More Answers (2)
Jan
on 31 May 2011
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...
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!