Replace values in a matrix

조회 수: 5 (최근 30일)
KF
KF 2020년 12월 14일
댓글: Rik 2020년 12월 14일
Hi,
I have a 250x250 matrix, each cell having either 1,2,3,4,5 or NaN, derived from kmeans index. I'm looking to reorder my kmeans values and have found a new order for these values based on populatation e.g. 3 4 5 2 1, 3 being most populated, 1 being least. I'm looking for a way to tell the system to make 3 the new 1, 4 the new 2 etc.. i.e. replace all 3s with 1, all 4s with 2, all 5s with 3, all 2s with 4, all 1s with 5. However, when I use a loop, I end up losing data as it thinks the converted numbers were my original ones and replaces them to a new value.
  댓글 수: 2
KALYAN ACHARJYA
KALYAN ACHARJYA 2020년 12월 14일
"I end up losing data as it thinks the converted numbers were my original ones and replaces them to a new value"
Copy the data with temp variable. The initial part of the question is not clear to me. Please make it easy to understand with simple examples.
KF
KF 2020년 12월 14일
So, let's say for simplicity I have a 10x10 matrix,
A = [ ]
NaN NaN NaN 3 3 3 2 NaN NaN NaN
NaN 4 4 3 3 3 3 3 NaN NaN
NaN NaN 4 3 3 3 5 2 NaN NaN
NaN 3 3 3 3 1 3 3 3 NaN
4 1 4 2 5 5 5 3 NaN NaN
4 2 4 3 5 5 5 3 3 NaN
NaN 2 4 3 3 3 3 3 NaN NaN
NaN 3 3 3 2 1 5 4 NaN NaN
NaN NaN NaN 3 1 4 1 3 NaN NaN
NaN NaN NaN 3 3 3 3 3 NaN NaN
How would I replace all the 3s with 1, all of the 4s with 2, all of the 5s with 3, all of the 2s with 4 and all of the 1s with 5.
The NaNs should stay as they are.

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

채택된 답변

Rik
Rik 2020년 12월 14일
Because you are only using integers, you can even use indexing to do the replacement:
A=[NaN NaN NaN 3 3 3 2 NaN NaN NaN
NaN 4 4 3 3 3 3 3 NaN NaN
NaN NaN 4 3 3 3 5 2 NaN NaN
NaN 3 3 3 3 1 3 3 3 NaN
4 1 4 2 5 5 5 3 NaN NaN
4 2 4 3 5 5 5 3 3 NaN
NaN 2 4 3 3 3 3 3 NaN NaN
NaN 3 3 3 2 1 5 4 NaN NaN
NaN NaN NaN 3 1 4 1 3 NaN NaN
NaN NaN NaN 3 3 3 3 3 NaN NaN];
dict=[5 4 1 2 3];
L=~isnan(A);
A(L)=dict(A(L))
A = 10×10
NaN NaN NaN 1 1 1 4 NaN NaN NaN NaN 2 2 1 1 1 1 1 NaN NaN NaN NaN 2 1 1 1 3 4 NaN NaN NaN 1 1 1 1 5 1 1 1 NaN 2 5 2 4 3 3 3 1 NaN NaN 2 4 2 1 3 3 3 1 1 NaN NaN 4 2 1 1 1 1 1 NaN NaN NaN 1 1 1 4 5 3 2 NaN NaN NaN NaN NaN 1 5 2 5 1 NaN NaN NaN NaN NaN 1 1 1 1 1 NaN NaN
  댓글 수: 2
KF
KF 2020년 12월 14일
Perfect, thank you!! Knew there would be a simplified way :)
Rik
Rik 2020년 12월 14일
You're welcome. If you happen to have an equivalent problem with non-integers; you can use unique to generate a list of indices (use the first and third output).

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

추가 답변 (1개)

David Hill
David Hill 2020년 12월 14일
a=A==1;
b=A==2;
A(A==3)=1;
A(A==4)=2;
A(A==5)=3;
A(b)=4;
A(a)=5;

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by