Replace all numbers in a matrix
There are two matrices; the first is my input matrix

and the second ("rename matrix") is used to replace the values of the first

That is, looking at the rename matrix; 701 should be replaced with 1, ..., 717, should be replaced with 10, etc. so that the input matrix becomes as such

What? the values are defined, but I didn't put them. The second column of the input matrix is already sorted (ascending from top to bottom), but the values are not sequential (no "710": see first figure).
The question is how to get the output matrix (last pic) from the first two.
It looks to me like it's screaming about a sparse matrix solution. In Matlab, you can create a sparse matrix with the following command:
SM = sparse( ri, ci, val );
where ri is the row index of nonzero elements, ci is the corresponding column index, and val are the values.
Let's call your input matrix IM
and your search matrix LUM
, then we'll build a sparse matrix:
nr = size(LUM, 1);
SM = sparse( ones(nr, 1), LUM(:, 1), LUM(:, 2) );
Now we can get the result in one line:
newMatrix = reshape(SM(1, IM), size(IM));
almost magic.
I haven't had a chance to test this tonight, but if it doesn't work exactly as described, it should be really very close ...
If the values in the first column appear in the second column, and if all you need is to replace the values in the second column with 1..n
and change the values in the first column accordingly, you can do it all with a simple call ismember
:
%# define "inputMatrix" here as the first array in your post
[~,newFirstColumn] = ismember(inputMatrix(:,1),inputMatrix(:,2));
To build your output you have to write
outputMatrix = [newFirstColumn,(1:length(newFirstColumn))'];
If M
is original matrix and R
is rename matrix, this is how you do it
N = M;
for n = 1:size(M,1)
N(find(M==R(n,1))) = R(n,2);
end
Note that in this case you are creating a new matrix N
with renamed values. You don't have to do this if you want to.