How to create cell-array in MATLAB and initialize all elements to the same object?

南笙酒味 提交于 2019-12-10 02:09:38

问题


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

回答1:


You can do this with deal().

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

X = 

    [3x3 double]
    [3x3 double]
    [3x3 double]



回答2:


An alternative way:

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

another one:

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



回答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)};


来源:https://stackoverflow.com/questions/8195641/how-to-create-cell-array-in-matlab-and-initialize-all-elements-to-the-same-objec

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!