Reputation: 1153
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?
Upvotes: 2
Views: 3592
Reputation: 1241
Your code contains several problems:
First is shown in @angainor answer. You need to convert string to number.
Second one is following. B{i} is matrix of size 7x1, A{j,2} is single number. Do you want to add this number to all elements of matrix B{i}? In this case, you should write something like:
B{i} + str2double(A{j,2}) * ones(size(B{i}))
Third problem is that length(A) command will return total number of elements in A, e.g. 4*2=8. Therefore, you will have error: Can not access element A{5,2}. You need replace this line with
for j = 1:size(A,1)
Upvotes: 1
Reputation: 11810
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
.
Upvotes: 3