Hello !
I am trying to vectorize this nested for loop but I cannot think of any solution.
L=zeros(4,200,3);
for i=1:3
for p=4:200
for q=1:4
L(q,p,i)=G(p-q+1,i);
end
end
end
What I tried (but doesnt work) :
L = zeros(4,200,3);
[p,q] = ndgrid([4:200],[1:4]);
p = p(:);
q = q(:);
L(q,p,:)=G(p-q+1,:);
Can someone please help me with what is wrong with my logic ?

 採用された回答

Voss
Voss 2022 年 6 月 11 日

0 投票

% random matrix G:
G = rand(200,3);
[r,m] = size(G);
% parameter:
n = 4;
% for loop method (generalized):
L=zeros(n,r,m);
for i=1:m
for p=n:r
for q=1:n
L(q,p,i)=G(p-q+1,i);
end
end
end
% vectorized method:
p = n:r;
q = 1:n;
idx = p(:).'-q(:)+1 + reshape(0:m-1,[1 1 m])*r;
L_vectorized = [zeros(n,n-1,m) G(idx)];
% check that the two methods give the same result:
isequal(L,L_vectorized)
ans = logical
1

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

製品

タグ

質問済み:

2022 年 6 月 9 日

回答済み:

2022 年 6 月 11 日

Community Treasure Hunt

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

Start Hunting!

Translated by