필터 지우기
필터 지우기

Function to compute product of all numbers from 1 to n

조회 수: 34 (최근 30일)
Dobs
Dobs 2021년 11월 22일
댓글: Dobs 2021년 11월 22일
Hi,
I'm trying to solve the following problem: "Write a Matlab function that recursively computes the product of the integers from 1 to n". My code isnt' working though. This is what I got so far:
function r = integerproduct (n)
b = 1;
vector = 1:n;
for i = 1:length(vector)
while i <= 5
q = vector(i)*vector(i+b)
end
b=b+1;
r = q*vector(i+b)
end
end
I just used n = 5 as an example. If I understand the exercise correctly, the function is supposed to compute the following: 1*2*3*4*5 = 120.
It takes forever to run the code which seems a bit dodgy, surely it's not supposed to take that long? Does anyone have any hints as to what I should change so that 1) the function actually does what it's supposed to do and 2) the code runs as efficiently as possible?
Many thanks,
Dobs

채택된 답변

Matt J
Matt J 2021년 11월 22일
integerproduct(5)
ans = 120
function r = integerproduct (n)
if n==1, r=1; return; end
r=n*integerproduct(n-1);
end
  댓글 수: 3
Matt J
Matt J 2021년 11월 22일
편집: Matt J 2021년 11월 22일
The function is already used inside the function itself?
Yes, that's what recursion is.
Dobs
Dobs 2021년 11월 22일
Oh, I thought it meant that the function keeps going until n is reached (whatever n is). Thank you for clarifying!

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by