Matlab:将不同长度的向量添加到矩阵中

时间:2013-03-20 09:28:52

标签: matlab vector matrix concatenation

是否可以为矩阵自动添加长度不同的矢量?

即:

a = [1 2 3 4]
b = [1 2]

如何让C成为:

c = [1 2 3 4 ; 1 2 0 0]

c = [1 2 3 4 ; 1 2 NaN NaN]

或类似的东西

由于

2 个答案:

答案 0 :(得分:3)

这可能会有所帮助

a = [1 2 3 4];
b = [1 2];
c = a;
c(2,1:length(b)) = b;

c =

 1     2     3     4
 1     2     0     0

然后,如果你宁愿NaN而不是0,你可以做丹尼斯·贾赫鲁丁在下面的评论中所建议的。

答案 1 :(得分:1)

制作这样的功能

function out = cat2(a, b)

    diff = length(a) - length(b)
    if diff > 0
        b = [b, nan(1, diff)];
    else
        a = [a, nan(1, -diff)];
    end

    out = [a;b];

end

(但也添加了一个检查以处理列向量)

cat2([1 2 3 4], [1 2])

ans =

     1     2     3     4
     1     2   NaN   NaN