0

I want to use the numeric array such as 1:7 to create a cell array such as {1,2,3,4,5,6,7}. How can I do it? By which function?

Wrong

>> {1:2}

ans = 

    [1x2 double]

Correct output

>> {1,2}

ans = 

    [1]    [2]
hhh
  • 50,788
  • 62
  • 179
  • 282

2 Answers2

4

You can use

num2cell(1:7)

which converts every number to a single element in the output cell.

There are more things you can do with it; type help num2cell for more info.

There's a bunch of alternative approaches, the easiest I think would be

arrayfun(@(x)x, 1:7, 'UniformOutput', false)

or the good old for loop:

N = 7;

C = cell(N,1);
for ii = 1:N
    C{ii} = ii; end

Despite what you hear about for loops in MATLAB, they are not so terrible anymore. If you repeat Nick's test for larger N, you'll see that num2cell is fastest, then the for loop, and then arrayfun.

Rody Oldenhuis
  • 37,726
  • 7
  • 50
  • 96
2

n my view there are two ways to do this. num2cell is by far the best method, but I'd like to mention the arrayfun method as well.

>> arrayfun(@(a)(a), 1:7, 'UniformOutput', false);


>> num2cell(1:7);
Nick
  • 3,143
  • 20
  • 34
  • Note that if you increase the size to say, `1:1e6`, it is `num2cell` that clearly wins. – Rody Oldenhuis Sep 05 '13 at 14:20
  • @RodyOldenhuis I agree... but the `tic` `toc` is not the main reason I have mentioned it. But I have removed it now. Arrayfun can be a very useful function throughout Matlab. It seems that hhh is learning matlab. So let's help him as much as possible. :) – Nick Sep 05 '13 at 14:21