MATLAB Combine matrices of different dimensions, f

2019-07-17 01:49发布

问题:

I have two matrices, 22007x3 and 352x2. The first column in each is an index, most (but not all) of which are shared (i.e. x1 contains indices that aren't in x2).

I would like to combine the two matrices into a 22007x4 matrix, such that column 4 is filled in with the values that correspond to 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 something along the lines of

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

but firstly I get the error

??? Subscripted assignment dimension mismatch.

and then I can't figure out I would fill the rest of it.

An important point is that there are not necessarily an equal number of rows per index in my data.

How might I make this work?

回答1:

Taking Amro's answer from here

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

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

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

get the relevant values using these row indices but excluding the zeros, hence the loc > 0 mask. You have to exclude these as 1, they are not in x2 and 2 you can't index with 0.

Make a new column of default values to stick on the end of x1. I think NaN() is probably better but zeros() is also fine maybe

newCol = NaN(size(x1,1),1)

Now use logical indexing to get the locations of the non zero elements and put a in those locations

newCol(loc > 0) = a

Finnaly stick it on the end

x3 = [x1, newCol]