sorting and selecting data within a matrix to match two columns.

20 次查看(过去 30 天)
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.

回答(1 个)

KSSV
KSSV 2016-3-8
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

类别

Help CenterFile Exchange 中查找有关 Shifting and Sorting Matrices 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by