# MATLAB, help debugging my code.

I'm asked to create a function that accepts any number of inputs, then computes the sum of all the arguments. I am asked to test the function using the four arrays, a,b,c,d defined in the calling program. Here is my code:

function totalsum = cellsum(varargin)
%Purpose: Create a function that a accepts an arbitrary number of elements
%and sums the elements of the arguments together.

%Determine number of arguments
n = nargin;

%Set varargin to a vector,x

x = varargin;

%Allocate space
arraysum = zeros(1,n);
%Calculate the sum of each argument using a for loop.
for ii = 1:n
arraysum(ii) = sum(x{ii});
end%for

%Calculate total sum
totalsum = sum(arraysum);
end%function

%Purpose: Write a calling program for function cellsum using given data.

%Define given data.

a = 10;
b = [4;-2;2];
c = [1 0 3; -5 1 2; 1 2 0];
d = [1 5 -2];

%Call program

callsum = cellsum(a,b,c,d);

%print result
fprintf('Total sum is %f.\n' , callsum)

When I run this, I get these errors:

??? In an assignment A(I) = B, the number of elements in B and
I must be the same.

Error in ==> cellsum at 17
arraysum(ii) = sum(x{ii});

Error in ==> hw10num4 at 12
callsum = cellsum(a,b,c,d);

Thanks for the guidance!

It's been a while since I've done any MATLAB, so I'm not sure how best to fix it. But I do see the source of the error.

To see it, try and do a sum on the c matrix.
Code:
>>> sum(c)
ans =

-3   3   5

Notice how it's returning a vector with the sum of each column? You're expecting a scalar but you're getting a vector back. Hence the error.

Oh, I didn't realize that it summed columns. Thank you! I can easily fix it now!

Oh, I didn't realize that it summed columns. Thank you! I can easily fix it now!