Replace elements of matrix

조회 수: 16(최근 30일)
Ionut  Anghel
Ionut Anghel 2013년 3월 3일
댓글: Mike Lynch 2020년 11월 24일
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:
for i=1:numel(matrix)
for j=1:length(vector)
if matrix(i)==valvect
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
Mike Lynch
Mike Lynch 2020년 11월 24일
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
else ...

댓글을 달려면 로그인하십시오.

채택된 답변

Youssef  Khmou
Youssef Khmou 2013년 3월 3일
hi, try ;
for i=1:length(vector)
  댓글 수: 5
Walter Roberson
Walter Roberson 2019년 4월 12일
If you use ismember() with two outputs, then the second output is the index at which the element in the first parameter appears in the second parameter. In places that the element does not occur, then the returned value will be 0 there. You can select just the valid indices by indexing the second output by the first output.
[is_it_there, idx] = ismember(A, B);

댓글을 달려면 로그인하십시오.

추가 답변(4개)

Metin Ozturk
Metin Ozturk 2018년 8월 1일
The more vectorized and easier way to do this could be as follows:
new_matrix = changem(matrix,zeros(length(vector),1),vector);
  댓글 수: 2
BJ Anderson
BJ Anderson 2019년 3월 12일
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
Bruno Luong 2019년 3월 12일
F = matrix .* ~ismember(matrix,vector)
  댓글 수: 1
Bruno Luong
Bruno Luong 2019년 3월 13일
A variant is:
matrix(ismember(matrix,vector)) = 0

댓글을 달려면 로그인하십시오.

Walter Roberson
Walter Roberson 2013년 3월 3일
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
Image Analyst 2013년 3월 3일
Try it this way:
newMatrix = matrix % Initialize
for k = 1 : length(vector)
newMatrix(matrix==vector(k)) = 0
  댓글 수: 1
Ionut  Anghel
Ionut Anghel 2013년 3월 3일
Thanks It is working as well

댓글을 달려면 로그인하십시오.


Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by