Replace elements of matrix
Afficher commentaires plus anciens
I have the folowing:
vector=[1 3 8 9];
matrix=[ 100 1 5 9 6; 100 10 13 3 8; 100 9 10 1 4; ];
% I want to search and replace the vector element with "0"in the matrix (i.e new matrix should be : Newmatrix=[ 100 0 5 0 6; 100 10 13 0 0; 100 0 10 0 4; ]; )
The script is:
Newmatrix=zeros(size(matrix));
for i=1:numel(matrix)
for j=1:length(vector)
valvect=vector(j);
if matrix(i)==valvect
Newmatrix(i)=0;
else
Newmatrix(i)=matrix(i);
end
end
end
The results is not the desired one but:
Newmatrix=100 1 5 0 6
100 10 13 3 8
100 0 10 1 4
So what I'm doing wrong?
Thank you
1 commentaire
Mike Lynch
le 24 Nov 2020
The accepted answer or changem are cleaner and more compact, but for the code you wrote the addition of a "break" should fix the problem.
if matrix(i)==valvect
Newmatrix(i)=0;
break
else ...
Réponse acceptée
Plus de réponses (4)
Metin Ozturk
le 1 Août 2018
1 vote
The more vectorized and easier way to do this could be as follows:
new_matrix = changem(matrix,zeros(length(vector),1),vector);
2 commentaires
BJ Anderson
le 12 Mar 2019
YES YES YES. It looks like hardly anyone knows about changem...I see similar questions asked and typically the "solution" involves a loop. A loop in MATLAB is the first sign you're doing something wrong.
changem covers so many situations, and it is elegant and concise, not to mention avoids the risk of re-reassigning an element.
changem is almost always the right anwer. Let the world know!
Thanks Metin for helping to spread the word.
BJ Anderson
le 12 Mar 2019
A quick update on changem:
Sadly, if one inspects the actual code within changem, it functions as a loop. While it is a handy one-liner, it does not have the time-savings of moving from a looped function to an matrix-operation function.
Bruno Luong
le 12 Mar 2019
F = matrix .* ~ismember(matrix,vector)
1 commentaire
Bruno Luong
le 13 Mar 2019
A variant is:
matrix(ismember(matrix,vector)) = 0
Walter Roberson
le 3 Mar 2013
0 votes
Suppose you set Newmatrix to 0 because matrix matched vector(1). Now what happens when you go on to the next j to test if matrix matched vector(2) ?
Image Analyst
le 3 Mar 2013
Try it this way:
newMatrix = matrix % Initialize
for k = 1 : length(vector)
newMatrix(matrix==vector(k)) = 0
end
1 commentaire
Ionut Anghel
le 3 Mar 2013
Catégories
En savoir plus sur Data Type Identification dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!