MATLAB, help debugging my code.

  • Thread starter btbam91
  • Start date
  • #1
91
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!
 

Answers and Replies

  • #2
297
2
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.
 
  • #3
91
0
Oh, I didn't realize that it summed columns. Thank you! I can easily fix it now!
 
  • #4
297
2
Oh, I didn't realize that it summed columns. Thank you! I can easily fix it now!

You're welcome, glad it helped.
 

Related Threads on MATLAB, help debugging my code.

Replies
16
Views
8K
Replies
1
Views
3K
  • Last Post
Replies
2
Views
9K
  • Last Post
Replies
0
Views
8K
  • Last Post
Replies
1
Views
5K
  • Last Post
Replies
14
Views
4K
  • Last Post
Replies
1
Views
1K
Replies
6
Views
4K
  • Last Post
Replies
0
Views
5K
  • Last Post
Replies
3
Views
2K
Top