speed up 3 nested for loops

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

 Respuesta aceptada

Roger Stafford
Roger Stafford el 10 de Mzo. de 2014

0 votos

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.

1 comentario

varun
varun el 15 de Mzo. de 2014
Thank you for those suggestion. It did improve the speed quite a bit and have replaced length with another variable.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Entering Commands en Centro de ayuda y File Exchange.

Preguntada:

el 10 de Mzo. de 2014

Comentada:

el 15 de Mzo. de 2014

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by