How can I change only the first min element in each row in a matrix?
조회 수: 1 (최근 30일)
이전 댓글 표시
Hi, I have a matrix and I want to replace the min element in each row with 0. I want to replace only the first min element in each each row, how can I do it? for example, if my matrix is: myMatrix = [5 10 2 5; 20 20 20 20]
I want to obtain: newMatrix= [5 10 0 5; 0 20 20 20]
thank you
댓글 수: 0
답변 (1개)
Deepak
2023년 7월 1일
You can achieve the desired result by using a loop to iterate over each row of the matrix and finding the minimum value using the min function. Once you have the minimum value, you can replace the first occurrence of that value with 0. Here's an example implementation:
myMatrix = [5 10 2 5; 20 20 20 20];
newMatrix = myMatrix; % Create a copy of myMatrix
% Loop through each row
for row = 1:size(myMatrix, 1)
% Find the minimum value in the current row
minVal = min(myMatrix(row, :));
% Find the column index of the first occurrence of the minimum value
colIndex = find(myMatrix(row, :) == minVal, 1);
% Replace the first occurrence of the minimum value with 0
newMatrix(row, colIndex) = 0;
end
% Display the new matrix
disp(newMatrix);
댓글 수: 1
DGM
2023년 7월 2일
편집: DGM
2023년 7월 2일
The min() function will already return the corresponding subscripts, so you don't need to search for it using find().
You could also avoid the loop if you wanted.
myMatrix = [5 10 2 5; 20 20 20 20];
% find column of first instance of min value in each row
[~,idx] = min(myMatrix,[],2);
% convert subscripts to indices to allow scattered indexing
sz = size(myMatrix);
idx = sub2ind(sz,1:sz(1),idx.');
% replace corresponding elements with zero
newMatrix = myMatrix;
newMatrix(idx) = 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!