How can I insert numbers 1-100 into the first column of a cell array?
91 views (last 30 days)
Show older comments
Brooke Yeager
on 14 May 2021
Commented: Brooke Yeager
on 14 May 2021
I know this sounds simple... maybe it's Friday and my brain is fried, so bare with me.
I have a cell array that is 100x8. I simply want the first column of this array to be numbers 1-100, such that the first row of the first column has a 1, the second row of the first column has a 2, the third row of the first column has a 3, and so on until the 100th row of the first column has 100. These numbers will correspond to the trial numbers.
I don't know why I can't figure this out.
1 Comment
the cyclist
on 14 May 2021
Don't feel bad. Even after decades of use of MATLAB, I sometmes have to tinker around to remember the exact syntax for different operations using cell arrays. (Even with the solution I proposed, I feel in the back of my mind that there is a simpler way.)
Accepted Answer
the cyclist
on 14 May 2021
Edited: the cyclist
on 14 May 2021
Here is one way:
N = 100;
% Set up an empty cell array
C = cell(N,8);
% Fill the first column
C(:,1) = num2cell(1:N)
3 Comments
the cyclist
on 14 May 2021
There is always more room in the "Here is one way but I think there is a better way" boat. I am regularly humbled here by the elegant solutions that are obvious (in retrospect).
More Answers (1)
DGM
on 14 May 2021
Someone can surely improve on this, but this is one way
C = cell(10,4) % i'm just going to use a smaller example array
C(:,1) = mat2cell((1:10).',ones(10,1),1)
gives
C =
10×4 cell array
{[ 1]} {0×0 double} {0×0 double} {0×0 double}
{[ 2]} {0×0 double} {0×0 double} {0×0 double}
{[ 3]} {0×0 double} {0×0 double} {0×0 double}
{[ 4]} {0×0 double} {0×0 double} {0×0 double}
{[ 5]} {0×0 double} {0×0 double} {0×0 double}
{[ 6]} {0×0 double} {0×0 double} {0×0 double}
{[ 7]} {0×0 double} {0×0 double} {0×0 double}
{[ 8]} {0×0 double} {0×0 double} {0×0 double}
{[ 9]} {0×0 double} {0×0 double} {0×0 double}
{[10]} {0×0 double} {0×0 double} {0×0 double}
See Also
Categories
Find more on File Operations in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!