How to make my Function work with vectors and scalers

1 view (last 30 days)
function [s] = myFactorial(inputArg1)
%myFactorial Summary of this function goes here
% Detailed explanation goes here
y = inputArg1;
if y==0;
s=1;
else;
for y = inputArg1
x = [y:-1:1];
s=0;
for i=1:length(x);
if s==0;
s=s+x(i);
else;
s=s*x(i);
end
end
end
end
end
I'm new to matlab and was tasked to create a factorial function. I'm only allowed to use for-loops.
  1 Comment
Walter Roberson
Walter Roberson on 28 Feb 2020
The task cannot be accomplished only using for-loops. You need assignment, and indexing, and multiplication. The task can be made much more efficient if you are also permitted to use at least one if test or one call to max()

Sign in to comment.

Answers (1)

Urmila Rajpurohith
Urmila Rajpurohith on 2 Mar 2020
As you mentioned that you allowed to use only for loops from that I am assuming that you are not allowed to use inbuilt “factorial” function.
you can use below code for finding factorial of a given number
function s = myFactorial(inputArg1)
s=1;
if inputArg1 == 0
s=1;
else
for i = 1: inputArg1
s=s*i;
end
end
end
  1 Comment
Walter Roberson
Walter Roberson on 2 Mar 2020
We discourage people from offering complete solutions to homework assignments.

Sign in to comment.

Tags

Community Treasure Hunt

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

Start Hunting!