Simil to VLOOKUP (but ismember index 0)

1 vue (au cours des 30 derniers jours)
Dave
Dave le 22 Nov 2014
Réponse apportée : Dave le 24 Nov 2014
Hello, I have array A 10x1 and array B 3x2 as below
A=[1; 2; 3; 4; 5; 6; 7; 8; 9; 10];
B=[2 100; 4 500; 7 300];
I need to add to the A matrix the values according to the second column of B.
Output should be
A=[1 NaN; 2 100; 3 NaN; 4 500; 5 NaN; 6 NaN; 7 300; 8 NaN; 9 NaN; 10 NaN];
Cannot use ismember because I will have a 0 index (*)
Is there a way to solve this? Thanks

Réponse acceptée

Guillaume
Guillaume le 22 Nov 2014
A simple way would be to fill the 2nd column of A with NaNs and replace some with logical addressing using ismember:
A=[1; 4; 3; 2; 5; 6; 7; 8; 9; 10]; %changed to make sure it works regardless of ordering
B=[2 100; 7 500; 4 300]; %changed to make sure it works regardless of ordering
A = [A nan(size(A, 1), 1)];
[row, locb] = ismember(A, B(:, 1));
A(row, 2) = B(locb(row), 2)
Another option is to use intersect instead of ismember and just use the indices it returns:
A=[1; 4; 3; 2; 5; 6; 7; 8; 9; 10]; %changed to make sure it works regardless of ordering
B=[2 100; 7 500; 4 300]; %changed to make sure it works regardless of ordering
A = [A nan(size(A, 1), 1)];
[~, ia, ib] = intersect(A, B(:, 1));
A(ia, 2) = B(ib, 2)

Plus de réponses (1)

Dave
Dave le 24 Nov 2014
Thanks a lot, that solves my problem.

Catégories

En savoir plus sur Matrices and Arrays dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by