필터 지우기
필터 지우기

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

조회 수: 1 (최근 30일)
Amine Ben Ayara
Amine Ben Ayara 2016년 3월 7일
답변: KSSV 2016년 3월 8일
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에서 Logical에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by