Adding values to 3d matrix

13 次查看(过去 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