How can I change only the first min element in each row in a matrix?
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
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 comentarios
Respuestas (1)
Deepak
el 1 de Jul. de 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 comentario
DGM
el 2 de Jul. de 2023
Editada: DGM
el 2 de Jul. de 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
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!