sorting and selecting data within a matrix to match two columns.
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
I have two matrices in which there are tow columns with unique identifiers. The 1st matrix is much bigger (207000*4) dimensions. The second is (14680*5). Column 1 from 1st matrix has values that appear more than once, and are identical to the values from column 1, matrix. I would like to attach the the two matrices by column one. So for example, if Column1, Matrix 1 value is 1650, then pick the row from Matrix 2 with same unique ID (1650) and add it to Matrix1 or into a new output matrix. Please see example excel table picture attached.
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/157017/image.png)
0 commentaires
Réponses (1)
KSSV
le 8 Mar 2016
clc; clear all ;
% Generate matrix1
pos1 = randsample(1:100,30)' ; % First column of matrix1 / id's
matrix1 = [pos1 rand(length(pos1),3)] ; % Data of matrix1
% Generate matrix2
pos2 = randsample(1:100,20)' ; % First column of matrix2 / id's
matrix2 = [pos2 rand(length(pos2),3)] ; % Data of matrix2
% Make new matrix from first columns of matrix1 and matrix2
newmatrix = [] ;
myidx = [] ;
% Loop for comparing id's
for i = 1:size(matrix1,1)
for j = 1:size(matrix2,1)
if matrix1(i,1) == matrix2(j,1)
myidx = [ myidx ; [i,j]] ;
end
end
end
% Indices which you need
[pos1(myidx(:,1)) pos2(myidx(:,2))]
% Get new matrix
newmatrix = zeros(size(myidx,1),7) ; % Initialize
for i = 1:size(myidx,1)
newmatrix(i,:) = [matrix1(myidx(i,1),1:end) matrix2(myidx(i,2),2:end)] ;
end
0 commentaires
Voir également
Catégories
En savoir plus sur Logical dans Help Center et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!