1
votes

I need some help to map elements from a short vector to a larger vector in Matlab. I can do this with a for-loop, but I'm sure there's a way to avoid this.

I have input vectors of same size: A = [ 2 3 5 ] and B = [ 0.1 0.3 0.23 ]. Vector A contains "index" and vector B data. A third input vector is given as C = [ 2 2 2 3 3 3 3 5 5 ] and now I want to generate the vector D = [ 0.1 0.1 0.1 0.3 0.3 0.3 0.3 0.23 0.23 ].

How can I, in Matlab, generate vector D, without using for-loops?

Thank you in advance!

3

3 Answers

1
votes

If the elements of the index vector are positive integers you can just use indexing:

idx(A,1) = 1:numel(A);
D = B(idx(C));

If A contains positive integers of large values you can use sparse matrix:

idx = sparse(A,1,1:numel(A));
D = B(idx(C));
2
votes
A = [2 3 5];
B = [0.1 0.3 0.23];
C = [2 2 2 3 3 3 3 5 5];

Use the second output of ismember to create an index vector:

[~, ind] = ismember(C, A);
D = B(ind);

Alternatively, use interp1:

D = interp1(A, B, C);
2
votes

You can also use unique to look up the index of each element in C, assuming that the values correspond to exactly the values in A. If A is not sorted then we have to sort the items of B first in order to match the indexing given by unique:

A = [2 3 5];
B = [0.1 0.3 0.23];
C = [2 2 2 3 3 3 3 5 5];

[~,isort] = sort(A);
Bsort = B(isort);    % sorted according to A
[~,~,k] = unique(C); % indices of items in C to pick from A
D = Bsort(k);        % each matching element from (sorted) B