필터 지우기
필터 지우기

For loop within a function?

조회 수: 73 (최근 30일)
Juan Marquez
Juan Marquez 2016년 3월 26일
댓글: Stalin Samuel 2016년 3월 26일
How can I put a for loop inside of a function? I'm trying to get the factorial of an input. Any given input.
Like if I pull up the function an put any number inside, to have its factorial be the output.

채택된 답변

Star Strider
Star Strider 2016년 3월 26일
A function is like any other script file, except it is saved as a function.
For example, to get the sum of the elements of a vector, this is one option using a for loop inside a function:
function p = vector_sum(x)
p = 0;
for k1 = 1:length(x)
p = p + x(k1);
end
end
Then call it as:
z = 1:10;
sum_from_1_to_10 = vector_sum(z)
You can adapt this idea to calculate the factorial for your assignment.
See the documentation for Function Basics for details.

추가 답변 (1개)

Stalin Samuel
Stalin Samuel 2016년 3월 26일
I don't understand why do you going for for loop instead of using the inbuilt factorial function
n = 3;%input value
f = factorial(n)
  댓글 수: 2
Juan Marquez
Juan Marquez 2016년 3월 26일
It's part of hw assignment
Stalin Samuel
Stalin Samuel 2016년 3월 26일
function f = fact(n)
f = 1;
for itr = 2:n
f = f*itr;
end
end
save the above code as separate file in your working directory and from main file use the below code to call the function
n = 3;%input value
f = fact(n)

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

카테고리

Help CenterFile Exchange에서 Environment and Settings에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by