A substitute for this 'for' loop

11 views (last 30 days)
Vijay
Vijay on 18 May 2017
Commented: Vijay on 18 May 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!

Accepted Answer

Roger Stafford
Roger Stafford on 18 May 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 Comment
Vijay
Vijay on 18 May 2017
Thank you very much for the answer! Cheers!

Sign in to comment.

More Answers (0)

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!