|
"Brandon Navra" <Braddon@sogetthis.com> wrote in message <fsb57i$4sg
$1@fred.mathworks.com>...
> Hi,
>
> I am currently working on a project that has a doubly-
> nested for loop. I wish to vectorize the loop as its takes
> too long, but am having problems doing so.
>
> Here is a snippet of the code
>
> for theta1 = -pi/3: pi/40: pi/3
> for theta2 = -2*pi/3: pi/40: 2*pi/3
> for theta3 = -pi/2: pi/40: pi/2
>
> x = 0.4*cos(theta1) + 0.4*cos(theta1 + theta2)...
> + 0.2*cos(theta1 + theta2 + theta3);
> y = 0.4*sin(theta1) + 0.4*sin(theta1 + theta2)...
> + 0.2*sin(theta1 + theta2 + theta3);
> xvec = [xvec,x];
> yvec = [yvec,y];
>
> end
> end
> end
>
> My idea is to create theta1, theta2, theta3 as arrays with
> all necessary values so I can just calculate the vectors in
> one line. Now, as far as I know, vector operations are
> element-wise, so to create the three arrays they would need
> an element for each potential value (in this case array
> length of 56889) and the values of the array would be
> repeated values in match the size.
>
> If the previous paragraph is confusing consider the
> following example:
>
> i = [1, 1, 1, 1, 1, 1, 1, 1, 1,...
> 5, 5, 5, 5, 5, 5, 5, 5, 5,...
> 9, 9, 9, 9, 9, 9, 9, 9, 9]
>
> j = [1, 1, 1, 5, 5 ,5, 9, 9, 9,...
> 1, 1, 1, 5, 5 ,5, 9, 9, 9,...
> 1, 1, 1, 5, 5 ,5, 9, 9, 9]
>
> k = [1, 5, 9, 1, 5, 9, 1, 5, 9,...
> 1, 5, 9, 1, 5, 9, 1, 5, 9,...
> 1, 5, 9, 1, 5, 9, 1, 5, 9]
>
> where i, j, k are all potential values (that the for loop
> could have)
>
> Any advice on how to create the three arrays would be
> greatly appreciated
>
> Thanks Braddon
----------
Use ndgrid:
[t3,t2,t1] = ...
ndgrid(-pi/2:pi/40:pi/2,-2*pi/3:pi/40:2*pi/3,-pi/3:pi/40:pi/3);
t1 = t1(:).'; t2 = t2(:).'; t3 = t3(:).'; % Make row vectors
xvec = 0.4*cos(t1)+0.4*cos(t1+t2)+0.2*cos(t1+t2+t3);
yvec = 0.4*sin(t1)+0.4*sin(t1+t2)+0.2*sin(t1+t2+t3);
You should note that, whereas the highest theta3 (t3) here will be pi/2, the
highest values of theta1 and theta2 will not be pi/3 and 2*pi/3, resp.,
because 40 is not divisible by 3.
Roger Stafford
|