Search code examples
matlabvectornumberscell

How to copy a vector of numbers in a cell in Matlab


I am using Matlab and I have some issues in doing a very simple task; I have a vector with some random numbers like this:

N = 3;
a = [33 61 97];

I want to copy the values of a inside the the cell defined as: A = cell(1,N); I know it is possible to copy the values from a to A by using a for loop but I am pretty sure it is not the most elegant way to do so. Is there an automatic way to reach my goal by using some specific functions or very few lines of code?

The output should be something like this:

A = [33] [61] [97];

Notice: I tried to do something like this: A{1,:} = a; but it did not work. Anyways I would like to reach my goal without using for loops please.

The code is:

N = 3;
a = [33 61 97];
A = cell(1,N)

Please do not change anything from the code but add only the lines required to fulfill the goal.


Solution

  • One way is to convert your a(1:N) to cell using num2cell :

    say example:

      N = 3;
      a = [33 61 97];
      A = {[] [] [];[] [] []; [] [] []};
      A(1,:) = num2cell(a(1:N))
    
      A = 
    
      [33]    [61]    [97]
      []      []      []
      []      []      []