How to Code with Preallocation, Vectorization and Only Calculating Once
Show older comments
Hello,
I have a code which needs speeding up and would like to get rid of my loops. How can I do this? I would like to preallocate, vectorize and only calculate it once. The code follows;
figure
for r = 0: 0.4: 3/2
r;
k=1;
for i=0:pi/2:2*pi;
theta= exp(i);
for j=0:pi/2:2*pi;
gamma= exp(j);
for deltas=i;j;k;
for t = 0
deltat= exp (t);
scatter3(r,theta,gamma,[]);
hold on
[i,j,k] = meshgrid(0: 3/2: 2*pi);
end
end
end
end
end
thank you.
Answers (2)
Jan
on 17 Feb 2013
0 votes
At first look at the MLint messages:
- deltat is not used at all, so omit the line which defines it.
- for t=0 is more expensive than simply set "t = 0;".
- r; wastes time only.
- for deltas=i;j;k is not a valid FOR loop. Perhaps you want: for deltas=[i,j,k], but this is guessed only.
Currently the program is not working correctly. Therefore it is not the time to care about pre-allocation or vectorization.
Categories
Find more on Entering Commands in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!