Adding values to 3d matrix

조회 수: 11 (최근 30일)
B
B 2012년 12월 23일
Dear all,
I have an emtpy 16x16x16 matrix, which i'm trying to update on the following locations:
x = [1,16,16]
y = [1,8,16]
z = [2,4,16]
The values are:
values =[1, 2, 1]
I have tried to do this as such:
matrix(x,y,z) = values
However, I get the following error:
Assignment has fewer non-singleton rhs dimensions than non-singleton subscripts
What am I missing here?
Any help would be greatly appreciated
Cheers

채택된 답변

Image Analyst
Image Analyst 2012년 12월 23일
편집: Image Analyst 2012년 12월 23일
That's not the way indexing works. It will go through every possible permutation of x, y, and z and then will expect to set it to a SINGLE value. Essentially you are specifying a rectangular block in the 3D matrix - a chunk out of the larger full 3D block. See this small demo:
m=rand(6,6,6)
m(1:3,2:4,3:5) = 0
Look where it put the zeros - not in just 3 elements, but in a whole block. So each element (in imaging we call it a voxel) should have one value, but you're trying to set three values equal to that value, not 1. If you don't want all permutations, use a for loop to take just one element from values and set it to the same index from x, y, and z, like this:
for k = 1 : length(x)
matrix(x(k), y(k), z(k)) = values(k);
end
  댓글 수: 2
B
B 2012년 12월 23일
Thanks for your reply,
I was hoping I could do it without a for loop, but it seems there is no way around it.
Image Analyst
Image Analyst 2012년 12월 24일
Don't worry about it. For only 3 iterations, it's not really a consideration - it'll be faster than a rocket powered cheetah on steroids. But if it were tens of thousands or millions of iterations, then you might try Roger's method - test it both ways to see which is faster.

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

추가 답변 (1개)

Roger Stafford
Roger Stafford 2012년 12월 24일
There is a way around for-loops using 'sub2ind'.
M = zeros(16,16,16);
M(sub2ind(size(M),x,y,z)) = values;
Roger Stafford

카테고리

Help CenterFile Exchange에서 Discontinuities에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by