MATLAB Answers

Assign value zero to n elements of cell array

508 views (last 30 days)
Karl on 17 Mar 2014
Commented: Benjamin on 12 Dec 2019
Hi all,
I am declaring a cell array to hold some numeric and non numeric data. I want to set the first row, all columns, equal to the numeric value zero. Something like this:
myCell = cell(5, 500);
myCell{1,:} = 0;
Which gives the error:
The right hand side of this assignment has too few values to satisfy the left hand side.
I've tried a number of other things, none worked, so have resorted to doing it in a loop. It works, but I really don't like it. Is there a simple way I'm missing?
Cheers, Karl


Sign in to comment.

Accepted Answer

Sean de Wolski
Sean de Wolski on 17 Mar 2014
myCell(1,:) = {0}
  • Left hand side: use () to keep it as cells not braces for extraction of the content of cells.
  • Right handside: make 0 a 1x1 cell so that it can be stuck into all of the cells on the left via scalar expansion


Show 1 older comment
chris oj
chris oj on 18 Oct 2018
This answer just helped me...thanks Sean.
Flavia Aluisi
Flavia Aluisi on 19 Nov 2019
This is valid also in the case where I have a cell with 10 columns and 71842 rows and I want to fill with the number one only the rows between 2695 and 2746 of column one?
Sean de Wolski
Sean de Wolski on 19 Nov 2019
@Flavia something like
myCell(2695:2746, 1) = {1}

Sign in to comment.

More Answers (2)

Jeffery Devereux
Jeffery Devereux on 7 Mar 2018
Nice! Thanks (Had the same issue) Never thought about using the curly brackets around the zero.


Sign in to comment.

Parna Bhattacharya
Parna Bhattacharya on 17 Mar 2018

  1 Comment

Benjamin on 12 Dec 2019
This also works:
A =
1 2 3
4 5 6
7 8 9
in order to zero the ith row: (i = 1)
A(1,:) = [0]
>> A =
0 0 0
4 5 6
7 8 9

Sign in to comment.


Translated by