sum of real numbers up to n using recursive code

조회 수: 15 (최근 30일)
Will Murphy
Will Murphy 2020년 2월 15일
댓글: Will Murphy 2020년 2월 16일
I'm trying to make more sense of recursive code as I have only very recently started using matlab. I was wondering how I would go about finding the sum of all real numbers up to x using recursive code, I have done it using if / for / while loops however after trying to self teach myself I would expect to go about this by:
function y = sum(x)
if x > 0
y = x * (x+1) / 2
end
elseif x <= 0
y = 'does not exist'
end
end
disp(y)
I understand that I am probably wrong, in which case how would I go better about this task. Any help would be appreciated.
  댓글 수: 2
Image Analyst
Image Analyst 2020년 2월 15일
편집: Image Analyst 2020년 2월 15일
You can edit the code to fix it you know. So go ahead and add the end.
How are you calling this? What is the initial value of x you're using? I assume the x are all integers, right? Is x a scalar or vector? And you have a finite number of them. Because the sum of all real numbers is infinite.
Will Murphy
Will Murphy 2020년 2월 16일
My apologies, x is a scalar what will equal where the integers finish.

댓글을 달려면 로그인하십시오.

채택된 답변

David Hill
David Hill 2020년 2월 15일
function x = t_sum(n)
x=1;
if n>1
x=n+t_sum(n-1);%recursive
end

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Function Creation에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by