views:

75

answers:

4

I want to create an 1,k cell of m,m matrices. I have some trouble trying to initialize it. My first idea was to do this

myCell = cell{1,K};
for k = 1:K
  myCell{1,k} = eye(m);
end 

But it seems like such ugly way to initialize it. There have to be a better way?

+1  A: 

Try this:

myCell =  mat2cell(repmat(eye(m),[1 k]),[m],repmat(m,1,k))
High Performance Mark
Awesome that did it!
Reed Richards
+1  A: 

Consider this one:

myCell = arrayfun(@(x)eye(m), 1:k, 'UniformOutput',false)
Amro
+2  A: 

A solution with even fewer function calls:

[myCell{1:k}] = deal(eye(m));
Jonas
+1: much simpler solution than either of the other two.
High Performance Mark
+1  A: 

Here's a very simple REPMAT solution:

myCell = repmat({eye(m)},1,K);

This simply creates one cell with eye(m) in it, then replicates that cell K times.

gnovice

related questions