MATLAB重整矩阵将索引转换为行索引 [英] MATLAB reshape matrix converting indices to row index

查看:402
本文介绍了MATLAB重整矩阵将索引转换为行索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将矩阵重塑为

x1 = 
    1   5
    3   4
    4   3
    7   1

成为

x2 =
    5
    NaN
    4
    3
    NaN
    NaN
    1

反之亦然,其中x1中的第一列是与x2中的行号相对应的索引?

or vice versa, where the first column in x1 is an index that corresponds to a row# in x2?

推荐答案

用NaN创建一个数组,并用值填充它:

Create an array with NaNs and fill it with values:

x2          = NaN(max(x1(:,1)),1);
x2(x1(:,1)) = x1(:,2);

现在,如果零填充是可以接受的,那么您可以直接使用第二行,而无需先创建out.

Now, if zero padding is acceptable, then you can simply use the second line directly without first creating out.

或者,对于您的特定示例(没有重叠的索引),可以通过以下方式获得相同的结果:

Alternatively, for your specific example (no overlapping indices) the same result is achieved with:

accumarray(x1(:,1),x1(:,2),[],[],NaN)

另辟

idx = ~isnan(x2);
x1  = [find(idx) x2(idx)];

这篇关于MATLAB重整矩阵将索引转换为行索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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