I would like to do the equivalent of
x = [1, 0, 3; 2, 3, 0; 0, 0, 3];
[yy, xx, vals] = find(x);
where I really need the vals
variable. I need all three, but vals
is important. Now consider the 3d case, and flip one, so it's more interesting.
x = repmat(x, [1, 1, 3]);
x(:, :, 2) = fliplr(x(:, :, 1));
I'd like to do the same as before. I found this in several places
[yy, xx, zz] = ind2sub(size(x), find(x));
but then I don't know how to extract vals
properly... I also don't really care about zz
, but I'm sure they somehow need to be used for indexing.
Any help would be appreciated.
find
with one output argument, as you used in your last statement:
[yy, xx, zz] = ind2sub(size(x), find(x));
returns linear indices into the matrix. You can use these to index:
index = find(x);
vals = x(index);
[xx,yy,zz] = ind2sub(size(x), index);
I'm not sure I've understood what you want to achieve, nevertheless, considering your last matrix x
x = [1, 0, 3; 2, 3, 0; 0, 0, 3]
z = repmat(x, [1, 1, 3]);
x(:, :, 2) = fliplr(x(:, :, 1))
with
[yy, xx, vals] = find(x)
you have:
yy
the indices of the rows of the found elements xx
the indices of the columns of the found elements then you can use
lin_idx=sub2ind(size(x),yy,xx)
to get the linear indices of the values inside the matrix x
now you can use
[a,b,c]=ind2sub(size(x),lin_idx)
to get the 3D indices of the elements in the matrix
You can access the values using that indices:
for i=1:length(a)
k(i)=x(a(i),b(i),c(i))
end
Now the array k
contains the values (as per the array vals
returned by find
).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.