Search code examples
arraysmatlabcell-array

loop in each cell array element in matlab


I haven't used cell arrays in Matlab and have question.

I have 2 cell arrays c and l. I want c to have 10 matrices of dimension 10 x 785. I want to loop through each row of the matrices in c.

For example, I want to replace each of these rows with another vector. How can I do it?

Here is the code that I currently have

k=10;
c={10};
l={10};
for v=1:10
  c{v}=rand(k,d);  
end
for a=1:10
    l{a}=zeros(k,1);
end
 for s=1 : 10
         for j=1:k
            l{s}=c{s,???}*xn';
         end
  end

in the final loop, I try to show which cell of c and l. But, how can I access each row of c{1}?


Solution

  • A cell reference can be used in any context where you'd use a full matrix. So to get the j'th row of a matrix M, you'd do the normal M(j,:). To get the j'th row of a matrix stored in cell array c, you do c{1}(j,:).

    So in your case, l{s}(j,:) = c{s}(j,:)*xn';

    Note that c={10} is not doing what you expect. You can either say c=cell(1,10), or you can clear c and let it build dynamically.

    Finally, since each of the matrices are the same size, consider a 3d matrix instead of a cell array. It will be perform better, and the syntax will be slightly more compact, and the particular operation you're doing will map to a matrix multiply:

    l = zeros(k, 1, 10);
    c = rand(k, d, 10);
    
    % Refer to c(:, :, 1) to get the first matrix