How to speed up iterating a large data in a nested loop ?
Show older comments
%example
a=1x1000;
b=1x1000;
for i=1:length(a)
for j 1:length(b)
x(i,j)=cos(a(i));
y(i,j)=sin(b(j));
end
end
Thank you and appreciate!
Answers (1)
Image Analyst
on 5 Dec 2020
Try this:
% Create sample data.
% numPoints = 500;
a = pi * rand(1, numPoints);
b = pi * rand(1, numPoints);
% Create x and y
x = repmat(cos(a(:)), [1, numPoints]);
y = repmat(sin(b), [numPoints, 1]);
% Display the x and y matrices:
cmap = jet(256);
subplot(2, 1, 1);
imshow(x, [], 'Colormap', cmap);
colorbar;
title('x', 'FontSize', 20);
subplot(2, 1, 2);
imshow(y, [], 'Colormap', cmap);
colorbar;
title('y', 'FontSize', 20);

2 Comments
Image Analyst
on 6 Dec 2020
If things depend on only k, and not j, then put them between the k and j loop, not inside the j loop.
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!