Converting a matrix into another by a mapping table

2 次查看(过去 30 天)
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 个)

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

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by