A substitute for this 'for' loop

11 ビュー (過去 30 日間)
Vijay
Vijay 2017 年 5 月 18 日
コメント済み: Vijay 2017 年 5 月 18 日
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!

採用された回答

Roger Stafford
Roger Stafford 2017 年 5 月 18 日
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 件のコメント
Vijay
Vijay 2017 年 5 月 18 日
Thank you very much for the answer! Cheers!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by