Converting a matrix into another by a mapping table

8 vues (au cours des 30 derniers jours)
Anthony Klinkert
Anthony Klinkert le 19 Fév 2018
Commenté : Anthony Klinkert le 19 Fév 2018
Hello Matlab experts! May I ask a question?
I need to change the values of the matrix a, for example
a =
3 4 2
3 4 1
4 1 2
Into the matrix, b
b =
5 6 3
5 6 2
6 2 3
By applying the mapping matrix, for example c
c =
1 2
2 3
3 5
4 6
In other words, how do I convert matrix a, into matrix b, by using the mapping in c to substitute values.
For example, the first element of a(1,1), 3, becomes a 5 in b(1,1) via the mapping matrix c. Like a lookup table, the second element of a(1,2), 4, becomes a 6 in b(1,2) by looking it up in matrix c. Etc.
The matrix a may grow to 1000s of columns and up to a million rows.
I slightly prefer vectorization over looping if possible.
Thanks so much!

Réponse acceptée

Jan
Jan le 19 Fév 2018
Modifié(e) : Jan le 19 Fév 2018
a = [3 4 2; ...
3 4 1; ...
4 1 2];
c = [1 2; ...
2 3; ...
3 5; ...
4 6]
m = c(:, 2);
Result = m(a)
This works if the first column of c does not matter, because it is 1:max(a(:)). Otherwise use this to create m:
m(c(:, 1)) = c(:, 2);
  1 commentaire
Anthony Klinkert
Anthony Klinkert le 19 Fév 2018
Thank you. I liked the simplicity of this approach.

Connectez-vous pour commenter.

Plus de réponses (1)

Image Analyst
Image Analyst le 19 Fév 2018
If the "a" and "c" are integers, you can use intlut() - a function meant for exactly this kind of operation. I show here for both cases: uint16 and uint8:
a = [3 4 2; ...
3 4 1; ...
4 1 2];
c = [1 2; ...
2 3; ...
3 5; ...
4 6]
% If using uint16:
lut = uint16([0; c(:, 2); zeros(65535 - size(c, 1), 1)]);
output = intlut(uint16(a), lut) % Or you can cast "a" to uint8 or int16
% If using uint8:
lut = uint8([0; c(:, 2); zeros(255 - size(c, 1), 1)]);
output = intlut(uint8(a), lut) % Or you can cast "a" to uint8 or int16
  1 commentaire
Anthony Klinkert
Anthony Klinkert le 19 Fév 2018
Thanks so much! I will use this when I run into scaling issues.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by