NimrodB
NimrodB

Reputation: 153

Matlab: Add vectors not in the same length to a matrix

Is it possible to automatically add vectors that are not in the same length together for a matrix?

i.e:

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

How can I make C to be:

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

or

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

or something like that

Thanks

Upvotes: 1

Views: 3658

Answers (2)

Dan
Dan

Reputation: 45752

Make a function like this

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

(but also add a check to handle column vectors too)

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

ans =

     1     2     3     4
     1     2   NaN   NaN

Upvotes: 1

High Performance Mark
High Performance Mark

Reputation: 78364

This might help

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

then, if you'd rather have NaN than 0, you could do what Dennis Jaheruddin suggests in a comment below.

Upvotes: 3

Related Questions