Converting a matrix into another by a mapping table

9 ビュー (過去 30 日間)
Anthony Klinkert
Anthony Klinkert 2018 年 2 月 19 日
コメント済み: Anthony Klinkert 2018 年 2 月 19 日
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!

採用された回答

Jan
Jan 2018 年 2 月 19 日
編集済み: Jan 2018 年 2 月 19 日
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 件のコメント
Anthony Klinkert
Anthony Klinkert 2018 年 2 月 19 日
Thank you. I liked the simplicity of this approach.

サインインしてコメントする。

その他の回答 (1 件)

Image Analyst
Image Analyst 2018 年 2 月 19 日
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 件のコメント
Anthony Klinkert
Anthony Klinkert 2018 年 2 月 19 日
Thanks so much! I will use this when I run into scaling issues.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by