how to search a value of a matrix and replace by vector value?

1 view (last 30 days)
hello everyone, it would be very kind of you if someone could help me to figure it out. i want to replace elements of matrix, the matrix contains student IDs.
if true
% code
User1 User2
84599 84607
151791 152219
151791 152195
357518 357809
357518 357863
end
the total number of users in the mentioned data is 8, one users may have many records in data.
if true
% code
84599 1
84607 2
151791 3
152195 4
152219 5
357518 6
357809 7
357863 8
end
I want to find one value like "84599" in all data and replace it by "1", then "84607" replace it by "2". The below result is the desired one
if true
% code
1 2
3 4
5 6
7 8
6 8
end
Thanks in advance
  1 Comment
Rik
Rik on 9 Nov 2017
The naive approach would be a for-loop, but if you take a look at ismember, you might be able to find a method of doing in one go with clever indexing.

Sign in to comment.

Accepted Answer

Eric
Eric on 9 Nov 2017
studentIDs = [84599 84607; ...
151791 152219; ...
151791 152195; ...
357518 357809; ...
357518 357863];
ID2code = [84599 1; ...
84607 2; ...
151791 3; ...
152195 4; ...
152219 5; ...
357518 6; ...
357809 7; ...
357863 8];
output = studentIDs;
for i=1:size(ID2code,1)
output(studentIDs==ID2code(i,1)) = ID2code(i,2);
end
The simple, straightforward approach. There may be more efficient ways, but this should get the job done.

More Answers (0)

Categories

Find more on Graphics Object Programming 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!