A substitute for this 'for' loop
11 次查看(过去 30 天)
显示 更早的评论
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!
0 个评论
采纳的回答
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
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!