Creating a 3D matrix by combination of a 3D matrix and a 2D matrix
조회 수: 2(최근 30일)
I'm trying to add data from a 2D matrix to an existing 3D matrix in my code.
My 3D matrix is 125x2x20 (125: # of the companies, 2: firms id and data, 20: # of years of data)
My 2D matrix is 2784x21 (2784: # of the companies, 21: firms id and 20 years of data)
Here's what I'm trying to do:
The number of row (125 for 3D and 2784 for 2D) represents the numbers of the companies ranging for 1 to 2784. In my 3D matrix I've narrow them to only the ones that I need and they are in a random order (ascending order of the data in column 2 for the 20 years).
My goal is to be able to identify the companies in the 2D matrix that are in the 3D one to add a colum in my 3D matrix which will end up in a 125x3x20. As you can understand, the 20 years of data in my 2D matrix correspond to the 20 years which represent the 3rd dimension of my 3D matrix. So, for each years, I would add a 3rd column in the 3D matrix that represent a different statistic.
Thanks for your help,
the cyclist 2021년 8월 18일
I think this does what you want:
% Set seed for reproducibility of this example
% Made-up data of the correct size
M3 = rand(125,2,20); % (125: # of the companies, 2: firms id and data, 20: # of years of data)
M2 = rand(2784,21);
% Create company ids that will match across the two arrays
M2(:,1) = randperm(2784);
M3(:,1,1) = randperm(125);
% Everything above this line is just making up some data.
% Everything below is the matching algorithm.
% Match up the corresponding companies across the two arrays
[hasMatch,indexToCompanyMatch] = ismember(M2(:,1),M3(:,1,1));
% Pull the matched company data from M2, and reshape to append to M3
matchedData = reshape(M2(hasMatch,2:end),125,1,20);
% Append matching data, ordered correctly
M3(indexToCompanyMatch(hasMatch),3,:) = matchedData;