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.

采纳的回答

Voss
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;
4. Using a 3D logical array for indexing in x (essentially the same as this answer by Matt J):
x(y(:,1,:) == 1 & [true false(1,size(y,2)-1)]) = 99;

更多回答(2 个)

Matt J
Matt J 2023-12-17
编辑:Matt J 2023-12-17
Possible? Yes. Advisable? Not so sure.
x(:,1,:)=x(:,1,:).*(y(:,1,:) ~= 1) + 99*(y(:,1,:) == 1);

Matt J
Matt J 2023-12-17
编辑:Matt J 2023-12-17
x( y(:,1,:)==1 & (1:width(y))==1 ) = 99;

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

产品


版本

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by