speed up 3 nested for loops
3 views (last 30 days)
Show older comments
Hi,
I have a matrix, called old_matrix, that is of size width = 500, length = 400, height = 50 and at each point in old_matrix (width,length,height) there is an intensity from 0-255.
I have to remap each point in the old matrix to a new matrix of size new_width = 500, new_length = 400, new_height = 400 * cosd(50) +10.
the function for mapping specific point of old_matrix(width,length,height) => new_matrix(width, length*cosd(height), length*sind(height))
This is the code I have so far
new_z = round((400*cosd(50)+10));
new_matrix = zeros(500,400,new_z);
for height = 50:-1:1
for width = 1:500
for length = 1:400
y_new = round(length*cosd(height));
if (y_new == 0)
y_new = 1;
end
z_new = round(length*sind(height));
if (z_new == 0)
z_new = 1;
end
current_val = old_matrix(width,length,height);
new_matrix(width,y_new,z_new) = current_val;
end
end
end
It works in terms of mapping the values however, it is very slow. Is it possible to vectorize this code to improve the speed for mapping? The intensities do not change, only the position of the intensity changes.
Thank you
0 Comments
Accepted Answer
Roger Stafford
on 10 Mar 2014
I think you have the nested for-loops in the wrong order for maximum efficiency. You are having to repeat the same computation on 'y_new' and 'z_new' 500 times for each combination of 'height' and 'length' indices. Do it this way instead:
for height = 50:-1:1
for length = 1:400
%Compute y_new & z_new here only once per 'height', 'length' comb.
new_matrix(:,y_new,z_new) = old_matrix(:,length,height);
end
end
Note: The word 'length' is a reserved word in matlab and shouldn't be used for a variable name. It is the name of one of its functions.
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements 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!