MATLAB组合不同维度的矩阵,填充相应索引的值 [英] MATLAB Combine matrices of different dimensions, filling values of corresponding indices

查看:412
本文介绍了MATLAB组合不同维度的矩阵,填充相应索引的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个矩阵,22007x3352x2.每个列的第一列都是一个索引,大多数索引(但不是全部)是共享的(即x1包含x2以外的索引).

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).

我想将两个矩阵合并为一个22007x4矩阵,以便在第4列中填充与两个原始矩阵中的特定索引相对应的值.

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.

例如:

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

成为

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);

但是首先我得到了错误

??? 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.

我怎么做这项工作?

推荐答案

此处获取Amro的答案

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

ismember的第二个参数返回x2中可以找到x1的每个元素的位置(如果找不到,则为0)

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);

使用这些行索引获取相关值,但不包括零,因此使用loc > 0掩码.您必须将它们排除为1,它们不在x2中,而2无法用0编制索引.

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.

在x1的末尾添加新的默认值列.我认为NaN()可能更好,但zeros()也可能很好

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)

现在使用逻辑索引获取非零元素的位置,并将a放在这些位置

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

newCol(loc > 0) = a

最后坚持到底

x3 = [x1, newCol]

这篇关于MATLAB组合不同维度的矩阵,填充相应索引的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆