MATLAB: I need help writing a matlab function

doit4mehomework

I need help writing a Matlab function that takes a positive integer n as its argument, and returns the sum of all odd numbers between 1 and n.

Best Answer

Hi Mateo
what about this
function sn=sum_odds(n)
narginchk(1,1);
if(n<0) || (n==0)
error(message('input error n<=0'));
end
if abs(n-floor(n))>0
error(message('input not +int'));
end
sn=sum([1:2:n])
% if rem(n,2)==0
% sn=sum([1:2:n-1])
% end

%
% if rem(n,2)>0
% sn=sum([1:2:n])
% end
end
if you find these lines useful would you please mark my answer as Accepted Answer
To any other reader, if you find this answer of any help please click on the thumbs-up vote link,
thanks in advance for time and attention
John BG