For loop within a function?
72 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Juan Marquez
el 26 de Mzo. de 2016
Comentada: Stalin Samuel
el 26 de Mzo. de 2016
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.
0 comentarios
Respuesta aceptada
Star Strider
el 26 de Mzo. de 2016
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.
0 comentarios
Más respuestas (1)
Stalin Samuel
el 26 de Mzo. de 2016
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 comentarios
Stalin Samuel
el 26 de Mzo. de 2016
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)
Ver también
Categorías
Más información sobre Environment and Settings en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!