MATLAB Answers

Diego R
0

Fill an array with different size vectors

Asked by Diego R
on 5 Sep 2019
Latest activity Answered by Jos (10584)
on 5 Sep 2019
I have different sized vectors and an array to fill
A=[1,2,3,4];
B=[5,6];
C=[7,8,9];
ARRAY=zeros(5);
And I want to reach this:
OBJECTIVE =
1 2 3 4 0
5 6 0 0 0
7 8 9 0 0
0 0 0 0 0
0 0 0 0 0
Any idea? Also if there is any way to extend vectors to certain length I highly appreciate to know.

  0 Comments

Sign in to comment.

4 Answers

Answer by Stephen Cobeldick on 5 Sep 2019
Edited by Stephen Cobeldick on 5 Sep 2019
 Accepted Answer

For an arbitrary number of vectors use a cell array, then looping is trivial:
>> D = {[1,2,3,4],[5,6],[7,8,9]};
>> M = zeros(5,5);
>> for k = 1:numel(D), M(k,1:numel(D{k})) = D{k}; end
>> M
M =
1 2 3 4 0
5 6 0 0 0
7 8 9 0 0
0 0 0 0 0
0 0 0 0 0

  0 Comments

Sign in to comment.


Answer by the cyclist
on 5 Sep 2019

Here is one straightforward way:
A=[1,2,3,4];
B=[5,6];
C=[7,8,9];
ARRAY=zeros(5);
ARRAY(1,1:numel(A)) = A;
ARRAY(2,1:numel(B)) = B;
ARRAY(3,1:numel(C)) = C;

  0 Comments

Sign in to comment.


Answer by Diego R
on 5 Sep 2019

Thank you both! I'd never had found this "numel" by myslef.

  0 Comments

Sign in to comment.


Answer by Jos (10584)
on 5 Sep 2019

A=[1,2,3,4];
B=[5,6];
C=[7,8,9];
[ARRAY, tf] = padcat(A,B,C) % pad with NaNs
ARRAY(~tf) = 0 % replace those NaNs with zeros
PADCAT concatenates vectors of unequal lengths by padding them with NaNs. It is available for free on the File Exchange

  0 Comments

Sign in to comment.