MATLAB: For loop within a function factorialfor loopfunction 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. Best Answer 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);endendThen 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. Related SolutionsMATLAB: How to fix the error Function definitions are not permitted at the prompt or in scripts. Write this part of code and save it as fact.mfunction y = fact(n)if n<=1 y=1;else y=n*fact(n-1)endthen call this function in Matlab Windows Commandn=5out=fact(n) MATLAB: For and while loops function F = getFacWhile(n) F=1; while n>1 F=F*n; n=n-1; endendfunction F = getFacWhile(n) F=1; for i=1:n F=F*i; endend Related QuestionWont the plot graph a lineInput and output functionSeries expansion: looping over different inputsHow to properly use sum to sum up microstates
Best Answer