How to make my Function work with vectors and scalers

1 次查看(过去 30 天)
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 个评论
Walter Roberson
Walter Roberson 2020-2-28
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()

请先登录,再进行评论。

回答(1 个)

Urmila Rajpurohith
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

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by