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 ?..

 채택된 답변

Walter Roberson
Walter Roberson 2016년 5월 24일

1 개 추천

d = accumarray(x(:,[2 1 3]), x(:,4), [m, n, p]);

댓글 수: 1

Marsellus Wallace
Marsellus Wallace 2016년 5월 24일
Arf, I've mastered bsxfun but accumarray still eludes me... Thanks !

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Jos (10584)
Jos (10584) 2016년 5월 24일

1 개 추천

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
Marsellus Wallace 2016년 5월 24일
편집: Marsellus Wallace 2016년 5월 24일
What would be best between using sub2ind and accumarray (other answer) ?
Jos (10584)
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
Marsellus Wallace 2016년 5월 24일
Well, I prefer sub2ind for readability but accumarray for conciseness. I'll test tomorrow for speed of execution but it was pretty quick already even with the loop, so...
Anyway, thanks !

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터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!

Translated by