How to add a column to a matrix by matching element (attached data)
Afficher commentaires plus anciens
Hi I have two matrices A and B with different sizes; B is smaller in size than A. I want to add another column to A by matching elements in both matrices. A small version of my data is as follows:
A=[
1 AUBURN 1 1.035108 1.035108 -64.410133
2 AUBURN 1 1.03706 1.03706 -65.261659
3 AUBURN 1 1.032929 1.032929 -66.801544
4 AUBURN 1 1.037436 1.037436 -65.328455
5 AUBURN 1 1.036071 1.036071 -64.403333
6 AUBURN 1 1.035108 1.035108 -64.410133
7 AUBURN 2 1.042328 1.042328 -64.042951
8 AUBURN 2 1.043484 1.043484 -64.622293
9 AUBURN 2 1.042239 1.042239 -64.048946
10 AUBURN 3 1.040954 1.040954 -64.565492
11 AUBURN 4 1.041164 1.041164 -64.526456
]
B=[
1 AUBURN 1 43.976116
2 AUBURN 2 44.100992
3 AUBURN 3 44.179913
4 AUBURN 4 44.143322
]
The second column in both matrices contain names that I want to be used for matching the elements in both matrices. I want the last column in B to be added to A with the corresponding matched elements. The results should be as C:
C=[
1 AUBURN 1 1.035108 1.035108 -64.410133 43.976116
2 AUBURN 1 1.03706 1.03706 -65.261659 43.976116
3 AUBURN 1 1.032929 1.032929 -66.801544 43.976116
4 AUBURN 1 1.037436 1.037436 -65.328455 43.976116
5 AUBURN 1 1.036071 1.036071 -64.403333 43.976116
6 AUBURN 1 1.035108 1.035108 -64.410133 43.976116
7 AUBURN 2 1.042328 1.042328 -64.042951 44.100992
8 AUBURN 2 1.043484 1.043484 -64.622293 44.100992
9 AUBURN 2 1.042239 1.042239 -64.048946 44.100992
10 AUBURN 3 1.040954 1.040954 -64.565492 44.179913
11 AUBURN 4 1.041164 1.041164 -64.526456 44.143322
]
Any idea?
Thanks
Réponse acceptée
Plus de réponses (2)
Assuming A and B are cell arrays, I loop through each row of B, find the corresponding rows in A, and insert the data from B.
% Add column to A
A(:,end+1) = {0};
% Loop through B and add to A as needed
for i = 1:size(B,1)
rowIdx = strcmp(A(:,2), B(i,2));
A(rowIdx,end) = B(i,3);
end
3 commentaires
Adam Danz
le 26 Juil 2018
Of course this
for i = 1:size(B,1)
rowIdx = strcmp(A(:,2), B(i,2));
A(rowIdx,end) = B(i,3);
end
Could be reduced to this
for i = 1:size(B,1)
A(strcmp(A(:,2), B(i,2)),end) = B(i,3);
end
Ismaeel
le 26 Juil 2018
Adam Danz
le 26 Juil 2018
That's why I'm assuming your data are stored in a cell array (or table) once you import them to Matlab, not a matrix. This solution will work of that's the case. JW's solution may be more appropriate if your data are stored in a table.
Ismaeel
le 26 Juil 2018
0 votes
Catégories
En savoir plus sur Logical dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!