I have a problem where my code works on matlab but does not on matlab grader could there be some type of reason for this.

13 views (last 30 days)
function y = mysum(n)
n=input('Enter an integer');
sum=0;
if n<0
y=-1;
disp('cannot input a negative number');
else for i=0:n
sum=sum+i;
end
y=sum;
end
here is my code it works for matlab but nor grader please help.

Accepted Answer

Image Analyst
Image Analyst on 3 Sep 2021
In addition to what Walter said, don't use "sum" as the name of your variable since it's a built-in function. And use k instead of i since sometimes we use i for the imaginary variable. Some corrections:
% Script to call the function for some n's.
for k = -1 : 3
fprintf('For n = %d, mysum(%d) = %d.\n', k, k, mysum(k));
end
%================================================================
function y = mysum(n)
y = 0;
if n < 0
y = -1;
errorMessage = sprintf('You cannot input a negative number, like %d', n)
uiwait(errordlg(errorMessage));
else
for k = 0 : n
y = y + k;
end
end
end

More Answers (1)

Walter Roberson
Walter Roberson on 3 Sep 2021
You should not be using input() there. The user should be passing the value of n when they invoke the function.
It would not be entirely unreasonable to use
function y = mysum(n)
if nargin < 1
n = input('Enter an integer');
end

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!