Azzera filtri
Azzera filtri

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

1 visualizzazione (ultimi 30 giorni)
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

Risposte (1)

Deepak
Deepak il 1 Lug 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 Commento
DGM
DGM il 2 Lug 2023
Modificato: DGM il 2 Lug 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

Accedi per commentare.

Categorie

Scopri di più su Dialog Boxes in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by