join - MATLAB Combine matrices of different dimensions, filling values of corresponding indices -


i have 2 matrices, 22007x3 , 352x2. first column in each index, (but not all) of shared (i.e. x1 contains indices aren't in x2).

i combine 2 matrices 22007x4 matrix, such column 4 filled in values correspond particular indices in both original matrices.

for example:

x1 =     1   1   5     1   2   4     1   3   5     2   1   1     2   2   1     2   3   2  x2 =     1   15.5     2   -5.6 

becomes

x3 =     1   1   5   15.5     1   2   4   15.5     1   3   5   15.5     2   1   1   -5.6     2   2   1   -5.6     2   3   2   -5.6 

i've tried along lines of

x3(1:numel(x1),1:3)=x1; x3(1:numel(x2(:,2)),4)=x2(:,2); 

but firstly error

??? subscripted assignment dimension mismatch. 

and can't figure out fill rest of it.

an important point there not equal number of rows per index in data.

how might make work?

taking amro's answer here

[~, loc] = ismember(x1(:,1), x2(:,1));  

ismember's second argument returns location in x2 each element of x1 can found (or 0 if can't)

a = x2(loc(loc > 0), 2); 

get relevant values using these row indices excluding zeros, hence loc > 0 mask. have exclude these 1, not in x2 , 2 can't index 0.

make new column of default values stick on end of x1. think nan() better zeros() fine maybe

newcol = nan(size(x1,1),1) 

now use logical indexing locations of non 0 elements , put a in locations

newcol(loc > 0) = 

finnaly stick on end

x3 = [x1, newcol] 

Popular posts from this blog

How to calculate SNR of signals in MATLAB? -

c# - Attempting to upload to FTP: System.Net.WebException: System error -

ios - UISlider customization: how to properly add shadow to custom knob image -