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

1 vue (au cours des 30 derniers jours)
Michal Somekh
Michal Somekh le 21 Déc 2017
Modifié(e) : DGM le 2 Juil 2023
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

Réponses (1)

Deepak
Deepak le 1 Juil 2023
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 commentaire
DGM
DGM le 2 Juil 2023
Modifié(e) : DGM le 2 Juil 2023
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

Connectez-vous pour commenter.

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by