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.

2
  • 1
    What does decent mean? Faster, fewer lines or...? Commented Oct 9, 2014 at 15:22
  • 1
    It means cleaner that my above solution. Yes, clean code is also a vague concept, but still an arguably useful one. Commented Oct 9, 2014 at 16:06

2 Answers 2

4

If you want to avoid arrayfun, you could do

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

or

C = cell(dim);
[C{:}] = deal(val);
Sign up to request clarification or add additional context in comments.

1 Comment

O.o Oh... deal()... Thats quite useful! +1
2

A simpler alternative:

C = repmat({val}, dim);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.