MATLAB, help debugging my code.

AI Thread Summary
The discussion revolves around debugging a MATLAB function designed to compute the sum of an arbitrary number of input arguments. The user encounters an error when trying to sum elements from a matrix, specifically the columns of matrix 'c', which returns a vector instead of a scalar. This discrepancy leads to an assignment error in the code. The solution involves recognizing that the `sum` function in MATLAB sums columns by default, and the user can adjust their approach to handle this correctly. The conversation concludes with the user expressing gratitude for the clarification, indicating they can now resolve the issue.
btbam91
Messages
91
Reaction score
0
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!
 
Physics news on Phys.org
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!
 
btbam91 said:
Oh, I didn't realize that it summed columns. Thank you! I can easily fix it now!

You're welcome, glad it helped.
 
Back
Top