Search code examples
arraysmatlabcell-array

Why does x={1:4} return a 1x1 cell and x={1 2 3 4} return a 1x4 cell? [MATLAB]


Why does x={1:4} return a 1x1 cell and x={1 2 3 4} return a 1x4 cell?

I would like to obtain a 1xn cell using x={1:n} statement. The reason is that I need to construct a struct

 struct('field1', [], 'field2', x, 'field3', ' message')

such that the struct is

enter image description here

The problem is if I use x={1:4}, the struct becomes

enter image description here

But I want the struct to look like the first picture. I need to use the x={1:n} statement as n can be very large.

Can anyone suggest a solution? Thank you in advance.


Solution

  • Since 1:4 gives the numeric vector [1 2 3 4], the assignment x = {1:4} is the same as x = {[1 2 3 4]}. So x is a 1×1 cell array containing a 1×4 vector.

    On the other hand, x = {1 2 3 4} creates a 1×4 cell array of numbers.

    To create something like x = {1 2 3 4} with varying size n, you can first create the numeric vector 1:n and then apply num2cell, which puts each number in a separate cell:

    x = num2cell(1:n);