How can I change only the first min element in each row in a matrix?

2 次查看(过去 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

回答(1 个)

Deepak
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
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
newMatrix = 2×4
5 10 0 5 0 20 20 20

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Dialog Boxes 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by