Assignment and indexing issue
古いコメントを表示
I have some data and their indexed coordinates in an array x :
% x(q,:) == [jq,iq,kq,xq]
I have an empty 3D matrix d in which I want to store these data, like so :
d = Inf(m,n,p);
for i=1:length(x)
d(x(i,2),x(i,1),x(i,3)) = x(i,4);
end
My question is, is there any way to do it without a loop ? I was thinking something like this but it does not work :
d = Inf(m,n,p);
d(x(:,[2,1,3])) = x(:,4);
Maybe throw a sub2ind or something in there somewhere ?..
採用された回答
その他の回答 (1 件)
Jos (10584)
2016 年 5 月 24 日
x = [1 1 1 10 ; 1 1 2 20 ; 2 3 2 30] % data
sz = max(x(:,1:3),[],1)
d = Inf(sz)
idx = sub2ind(sz,x(:,1),x(:,2),x(:,3))
d(idx) = x(:,4)
3 件のコメント
Marsellus Wallace
2016 年 5 月 24 日
編集済み: Marsellus Wallace
2016 年 5 月 24 日
Jos (10584)
2016 年 5 月 24 日
Both are fine. Compare them for readability, your understanding of the code, speed of execution, translation into other languages, etc.
Marsellus Wallace
2016 年 5 月 24 日
カテゴリ
ヘルプ センター および 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!