Search code examples
matrixsumcelloctave

Solve wrong type argument 'cell'


I write in variable 'O' some values using

for i = 1:size(I,1)
for j = 1:size(1,I)
h = i * j;
O{h} = I(i, j) * theta(h);
end
end

I - double, theta - double. I need to sum()all 'O' values, but when I do it its give me error: sum: wrong type argument 'cell'. How can I sum() it? P.s. when I want to see O(), its give me

O = 
{
  [1,1] =  0.0079764
  [1,2] =  0.0035291
  [1,3] =  0.0027539
  [1,4] =  0.0034392
  [1,5] =  0.017066
  [1,6] =  0.0082958
  [1,7] =    1.4764e-04
  [1,8] =  0.0024597
  [1,9] =    1.1155e-04
  [1,10] =  0.0010342
  [1,11] =  0.0039654
  [1,12] =  0.0047713
  [1,13] =  0.0054305
  [1,14] =    3.3794e-04
  [1,15] =  0.014323
  [1,16] =  0.0026826
  [1,17] =  0.013864
  [1,18] =  0.0097778
  [1,19] =  0.0058029
  [1,20] =  0.0020726
  [1,21] =  0.0016430 
etc...

Solution

  • The exact answer to your question is to use cell2mat

    sum (cell2mat (your_cell_o))
    

    However, this is the very wrong way to solve your problem. The thing is that you should not have created a cell array in first place. You should have created a numeric array:

    O = zeros (size (I), class (I));
    for i = 1:rows (I)
      for j = 1:columns (I)
        h = i * j;
        O(h) = I(i, j) * theta(h);
      endfor
    endfor
    

    but even this is just really bad and slow. Octave is a language to vectorize operations. Instead, you should have:

    h = (1:rows (I))' .* (1:columns (I)); # automatic broadcasting
    O = I .* theta (h);
    

    which assumes your function theta behaves properly and if givena matrix will compute the value for each of the element of h and return something of the same size.

    If you get an error about wrong sizes, I will guess you have an old version of Octave that does not perform automatic broadcasting. If so, update Octave. If you really can't, then:

    h = bsxfun (@times, (1:rows (I))', 1:columns (I));