12

I have a matrix (call it X) that is initialized to say zero(3).

I want to change the code so that X is a cell array of size (say) (3,1) and initialize each element to zero(3).

I can do it with a loop but is there a better way?

X = cell(3,1);
for ii=1:numel(X)
    X{ii} = zeros(3);
end
0

3 Answers 3

11

You can do this with deal().

>> [X{1:3, 1}] = deal(zeros(3))

X = 

    [3x3 double]
    [3x3 double]
    [3x3 double]
Sign up to request clarification or add additional context in comments.

1 Comment

Note that this is not safe if X already exists. For example if it was defined like this before [X{1:4, 1}] = deal(zeros(4))
11

An alternative way:

X = repmat({zeros(3)}, 3, 1);

another one:

X = cell(3,1);
X(:) = {zeros(3)};

1 Comment

The alternatives have the advantage that the size of X is determined on the same line as the new content. I would prefer them to deal. deal probably is best used in some other connection.
3

And yet another way:

X = {zeros(3)};
X(1:3,1) = X;

This solution uses the fact that you can assign to indices that lie beyond the variables size. Matlab will automatically expand in this case.

Similarly:

clear X;
X(1:3,1) = {zeros(3)};

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.