Tetra
Tetra

Reputation: 747

Add cells in cell array of matrices

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?

Upvotes: 0

Views: 1698

Answers (2)

yuk
yuk

Reputation: 19870

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

Upvotes: 1

Smash
Smash

Reputation: 3802

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

Upvotes: 1

Related Questions