A substitute for this 'for' loop

11 visualizaciones (últimos 30 días)
Vijay
Vijay el 18 de Mayo de 2017
Comentada: Vijay el 18 de Mayo de 2017
Could anyone shed some light on how this 'for' loop can be replaced by a single command in MATLAB?
for i=1:size(w,3)
x=w(:,:,i);
w1(i,:)=x(B(i),:);
end
clear x
Here, w is 3D (x by y by z) matrix and B (1 by z) is a vector containing rows pertaining to each layer in w. This 'for' loop takes about 150 seconds to execute when w is 500000 layers deep. I tried using,
Q = w(B,:,:);
Q = reshape(Q(1,:),[500000,2])';
This creates a matrix Q of size 500000 X 2 X 500000 and MATLAB threw me an error saying memory out of bound. Any help would be appreciated!

Respuesta aceptada

Roger Stafford
Roger Stafford el 18 de Mayo de 2017
It is important for efficiency’s sake that you initially allocate a sufficient amount of space for the w1 array before entering the for-loop:
[~,n2,n3] = size(w);
w1 = zeros(n3,n2); % <-- Initial memory allocation
for i=1:n3
w1(i,:)=w(B(i),:,i);
end
  1 comentario
Vijay
Vijay el 18 de Mayo de 2017
Thank you very much for the answer! Cheers!

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by