0

Code for creation of cell arrays taken from: Array of Matrices in MATLAB [Thank you Hosam Aly!]

The function is:

function result = createArrays(nArrays, arraySize)
    result = cell(1, nArrays);
    for i = 1 : nArrays
        result{i} = zeros(arraySize);
    end
end

My code:

   a=createArrays(49,[9,9]);

    a{1}(1,1) = 0.01 + 1.*rand(1,1);
    a{1}(2,2) = 0.01 + 1.*rand(1,1);
    a{1}(3,3) = 0.01 + 1.*rand(1,1);
    a{1}(4,4) = 0.01 + 1.*rand(1,1);
    a{1}(5,5) = 0.01 + 1.*rand(1,1);
    a{1}(6,6) = 0.01 + 1.*rand(1,1);
    a{1}(7,7) = 0.01 + 1.*rand(1,1);
    a{1}(8,8) = 0.01 + 1.*rand(1,1);
    a{1}(9,9) = 0.01 + 1.*rand(1,1);

I cannot use a{:}(1,1) to refer to all matrices. Matlab finds using { } an unexpected parenthesis when using loops.

I'd like to keep the format as above for the diagonal. What should I do?

Community
  • 1
  • 1
Tetra
  • 747
  • 2
  • 9
  • 15

2 Answers2

1

The best thing I can see is just to loop through all your cells:

for i = 1:49
 a{i}(1,1) = ...
end

But why use cells when you can just do a 3D matrix?

a = zeros(49,9,9);

a(:,2,2) = something
Smash
  • 3,722
  • 4
  • 34
  • 54
  • The rest of my code requires matrices to be stored in a cell array. The first part of your answer works, thanks! – Tetra Nov 02 '11 at 16:51
  • ok, but the second way is much faster if speed becomes a factor someday – Smash Nov 02 '11 at 16:55
1

To fill diagonal elements you don't have to do it one by one. use EYE function instead.

c1 = 1;
c2 = 0.01;
for i = 1:numel(a)
    a{i} = eye(size(a{i}) * c1 + c2;
end
yuk
  • 19,098
  • 13
  • 68
  • 99
  • Ah yes I understand. It's just that each diagonal element will be the result of different equations. Thanks for your advice though! – Tetra Nov 09 '11 at 11:39