Array within an array in MATLAB

If n=4

for example how to create such an array in MATLAB?

[[0] [0 0] [0 0 0] [0 0 0 0]]

      

Is there a way to create an array inside a loop for

for example? This is what I want to achieve (I know this is the wrong code):

for i=1:n
   table(i)=zeros(i);
end

      

+3


source to share


1 answer


You will need a cell array to store your numeric vectors . Array cells are used in Matlab when the contents of each cell are of a different size or type.

Additional comments:

  • I renamed the variable i

    to k

    to avoid shading the imaginary unit.
  • I also renamed the variable table

    to t

    to avoid function shading table

    .
  • zeros(k)

    gives a matrix of zeros k

    x k

    . To get a vector of strings of zeros use zeros(1,k)

    .
  • Better to preallocate the cell array to improve speed.

With that said, the code:

n = 4;
t = cell(1,n); %// preallocate: 1xn cell array of empty cells
for k = 1:n
   t{k} = zeros(1,k);
end

      



This gives:

>> celldisp(t)
t{1} =
     0
t{2} =
     0     0
t{3} =
     0     0     0
t{4} =
     0     0     0     0

      

Equivalently, you could replace the loop with a for

more compact one arrayfun

:

result = arrayfun(@(k) zeros(1,k), 1:n, 'uniformoutput', false);

      

+5


source







All Articles