4

I am looking for a decent way to create and initialize a cell array with a given value. I can think of the following oneliner

val = 'hello';
dim = [2, 4, 6];
arrayfun(@(x) val, zeros(dim), 'UniformOutput', false)

but I feel dirty.

P-Gn
  • 23,115
  • 9
  • 87
  • 104

2 Answers2

4

If you want to avoid arrayfun, you could do

C = cell(dim);
C(:) = {val};

or

C = cell(dim);
[C{:}] = deal(val);
MeMyselfAndI
  • 1,320
  • 7
  • 12
2

A simpler alternative:

C = repmat({val}, dim);
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147