Vectorized "find an replace"

12 ビュー (過去 30 日間)
Alexander Shtof
Alexander Shtof 2017 年 9 月 11 日
コメント済み: Guillaume 2017 年 9 月 11 日
I have a matrix `A` and an array `map`, both consist of integers. I would like to replace every entry where `A == i` with `map(i)`. I wrote the following non-vectorized code
Aorig = A;
for i = 1:numel(map)
A(Aorig == i) = map(i);
end
Is there a good way to vectorize it?

回答 (2 件)

Guillaume
Guillaume 2017 年 9 月 11 日
Assuming all values in A are valid indices for map, simply:
A = map(A);

Image Analyst
Image Analyst 2017 年 9 月 11 日
Well clearly A=map(Aorig) won't work. You have to use intlut(). Here's an example:
% Create sample data
Aorig = int16(randi(9, 20, 1))-1
% Initialize look up table for 16 bit signed integers:
map = zeros(65536, 1, class(Aorig));
% Now, enter your custom values at the proper locations.
% Map value for 0 should happen at index 32769 of map.
% Adjust positions to that that's true.
map((0:8)+32769) = int16([-9999,-8,-7,-6,-5,-4,-3,-2,-1]) % Just an example!
% B = Aorig(map) % Throws error.
A = intlut(Aorig, map)
This works and works not only for positive integers but for negative integers as well. Adjust map elements to create the lookup table that you want. I just used an arbitrary example.
  3 件のコメント
Image Analyst
Image Analyst 2017 年 9 月 11 日
It doesn't work for all values of A and map, for example negative or zero values. It doesn't work for values for where map is greater than the A either. For an all positive example where it doesn't work:
% Create 10 sample elements in the range [1, 3]
Aorig = int16(randi([1, 3], 10, 1))
% As an example, replace these A values with these replacement values.
% Replace 1's with 99, 2's with 0, 3's with 73.
map = int16([99, 0, 73]) % Just an example!
B = Aorig(map) % Throws error.
I got the impression the range of the A could be any integers, and the desired replacement values, in map, could also be any values that he desired to replace them with. My code will work for those conditions, I believe, while B=Aorig(map) doesn't.
Guillaume
Guillaume 2017 年 9 月 11 日
Well, clearly, from the code provided, the look-up values are always strictly positive. As I said, it wouldn't work for look-up values greater than the number of elements in map but it wouldn't make much sense to replace only part of the look-ups.
Note that the values of map are irrelevant. They can be positive, 0, negative, integer or non-integer.
In the OP case, I do believe that
map(A) %and not the opposite
would be the simplest solution.

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

カテゴリ

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

製品

Community Treasure Hunt

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

Start Hunting!

Translated by