Search code examples
matlabmatrixdimensionscell-array

How to add two cells in matlab


I have B <1x3 cell> like this:

B{1} = [2 1 19 22 29 13 14]
B{2} = [11 12 6 3 4 2 5]
B{3} = [3 2 23 13 4 7 8]

And I want to add A <4x2 cell> like this:

A = {'a' '-1'; 'b' '1'; 'c' '2'; 'd' ''}

I tried like this:

for j=1:length(A)
  for i=1:1:length(B)
    C = B{i} + A{j,2};
  end
end

what I get is "Matrix dimensions must agree." How can I do it properly?


Solution

  • A holds characters. You need to convert the strings to numbers to be able to add them to B. Use e.g. str2double:

    for j=1:length(A)
      for i=1:1:length(B)
        C = B{i} + str2double(A{j,2});
      end
    end
    

    Note that the last value in A is '', which is converted to a NaN.