how can i modify this short program so that it executes faster?
Show older comments
i have writen this program to vary theta between 0 to 180 n phi btw to 360 in steps of 0.5..n store those values from loop n plot..but this takes a really long time to execute..how can i modify so that it executes faster.
for j=10:5:3600
for i=10:5:1800
theta=(i/10)-1;
phi=(j/10)-1;
if (theta == 90)
r=1;
else
r=(((sind(270*cosd(theta))).^2))/((3* (sind(90*cosd(theta)))).^2);
end
x(j,i)=r*cosd(phi)*sind(theta);
y(j,i)=r*sind(phi)*sind(theta);
z(j,i)=r*cosd(theta);
end
end
plot3(x,y,z)
Accepted Answer
More Answers (1)
Andrei Bobrov
on 6 Oct 2011
theta =.5:.5:360;
phi =(0:.5:180)';
r = sind(270*cosd(theta)).^2./(3*sind(90*cosd(theta))).^2;
r(isnan(r)) = 1;
x = cosd(phi)*(r.*sind(theta));
y = sind(phi)*(r.*sind(theta));
z = r.*cosd(theta);
4 Comments
Jan
on 6 Oct 2011
I assume, this creates the wanted output, although the sizes of x,y,z differ from the original. The OP's arrays have the size [3600 x 1800], but contain mostly zeros.
Andrei Bobrov
on 6 Oct 2011
I noticed this and has ignored
Jan
on 6 Oct 2011
@Andrei: By avoiding the growing of the array, this solution needs 0.026 seconds, instead of 38.2 seconds of the original version. +1!
@Varshitha: The original version suffers from growing arrays: Increasing the size of an array in each iteration consumes a lot of time. Look for "pre-allocation" in this forum to learn more about this.
yashaswi
on 8 Oct 2011
Categories
Find more on Programming 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!