Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace all numbers in a matrix

There are two matrices; the first one is my input matrix

enter image description here

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

enter image description here

That is, looking at the renaming matrix; 701 must be replaced by 1,...,717 must be replaced by 10,etc.. such that the input matrix becomes as such

enter image description here

The ? values are defined but i didn't put them. The second column of the input matrix is already sorted(ascending order from top down) but the values are not consecutive(no "710": see first pic).

The question is how to get the output matrix(last pic) from the first two.

like image 363
K. Rmth Avatar asked Jan 30 '26 02:01

K. Rmth


2 Answers

Looks to me like it's screaming for 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 the non-zero elements, ci is the corresponding column index, and val is the values.

Let's call your input matrix IM and your lookup matrix LUM, then we construct the sparse matrix:

nr = size(LUM, 1);
SM = sparse( ones(nr, 1), LUM(:, 1), LUM(:, 2) );

Now we can get your result in a single line:

newMatrix = reshape(SM(1, IM), size(IM));

almost magic.

I didn't have a chance to check this tonight - but if it doesn't work exactly as described, it should be really really close...

like image 96
Floris Avatar answered Jan 31 '26 14:01

Floris


If the values in the first column all appear in the second column, and if all you want is replace the values in the second column by 1..n and change the values in the first column accordingly, you can do all of this with a simple call to ismember:

%# define "inputMatrix" here as the first array in your post

[~,newFirstColumn] = ismember(inputMatrix(:,1),inputMatrix(:,2));

To create your output, you'd then write

outputMatrix = [newFirstColumn,(1:length(newFirstColumn))'];
like image 42
Jonas Avatar answered Jan 31 '26 16:01

Jonas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!