Create an array based on the values in two other arrays

8 vues (au cours des 30 derniers jours)
Ziad Sari El Dine
Ziad Sari El Dine le 16 Juin 2022
Commenté : Voss le 16 Juin 2022
Hello, I have an array A(300x1) where the numbers vary between 1 and 198 in no particular order and some rows are nan other rows are repeated. Another array B(198x2) has in the first column 1:198 sorted in order and in the second column specific values for each row. I need to create an array C having the same size as A (300x1) however having the values from column 2 of array B where column 1 of B matches the value in array A. Example, if row 1 of array A is 90, i want row 1 in array C to have the value from column 2 of B where column 1 is 90 (row 90 in B).
Simplified example:
A [3 B[1 , 0.25 C[0.66
3 2 , 0.5 0.66
nan] 3 , 0.66 nan]
4 , 0.76]

Réponse acceptée

Voss
Voss le 16 Juin 2022
A = [3; 3; NaN];
B = [1 0.25; 2 0.5; 3 0.66; 4 0.76];
C = NaN(size(A));
[ism,idx] = ismember(A,B(:,1));
C(ism) = B(idx(ism),2);
disp(C);
0.6600 0.6600 NaN
  2 commentaires
Ziad Sari El Dine
Ziad Sari El Dine le 16 Juin 2022
Perfect, thanks.
Voss
Voss le 16 Juin 2022
You're welcome!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Matrix Indexing dans Help Center et File Exchange

Produits


Version

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by