How to replace elements of one dimension of an n-D matrix based on values in the same dimension of another n-D matrix of equal dimensions?
7 次查看(过去 30 天)
显示 更早的评论
I have two 3D matrices with identical dimensions, x and y. For e.g.
x = randi(10,3,2,10); %A (3X2X10) matrix of random numbers 1-10.
y = randi([0 1],3,2,10); %A (3X2X10) matrix of 0s or 1s. Identical dimension to x
I wish to replace any number in the first element of the 2nd dimension (i.e. in the '2' of 3X2X10) of 'x', wherever there is a '1' in the corresponding dimension of y, with a constant number, say, 99. So the logic is
replace any number in x(:,1,:) where (y(:,1,:) == 1) with '99'
I know we can do this by defining a third variable z, making changes, and replacing x elements with z:
z = x(:,1,:);
z(y(:,1,:) == 1) = 99;
z(:,1,:) = x(:,1,:);
But I want to know if this can be done in one line, without defining a third variable 'z' and directly doing it with x and y. Is it possible? Any help will be appreciated. Thank you.
0 个评论
采纳的回答
Voss
2023-12-17
Here are a few alternatives:
1: One-liner using linear indexing in x:
x(floor((find(y(:,1,:)==1)-1)/size(y,1))*prod(size(y,[1 2]))+mod(find(y(:,1,:)==1)-1,size(y,1))+1) = 99;
2. Same as #1 but with some convenient temporary variables:
idx = find(y(:,1,:)==1);
[m,n] = size(y,[1 2]);
x(floor((idx-1)/m)*m*n+mod(idx-1,m)+1) = 99;
3. Using ind2sub to get subscript indices in y(:,1,:), then sub2ind to convert those to linear indices in x:
[r,c,p] = ind2sub([size(y,1) 1 size(y,3)],find(y(:,1,:)==1));
x(sub2ind(size(y),r,c,p)) = 99;
x(y(:,1,:) == 1 & [true false(1,size(y,2)-1)]) = 99;
2 个评论
Torsten
2023-12-17
Shouldn't we initiate something similar for MATLAB programming ?
Dyuman Joshi
2023-12-24
That's a good idea, maybe TMW should pick this up as next year's community contest, lol.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!