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!