A substitute for this 'for' loop

11 vues (au cours des 30 derniers jours)
Vijay
Vijay le 18 Mai 2017
Commenté : Vijay le 18 Mai 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!

Réponse acceptée

Roger Stafford
Roger Stafford le 18 Mai 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 commentaire
Vijay
Vijay le 18 Mai 2017
Thank you very much for the answer! Cheers!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by