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
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
2020-3-2
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 个评论
Walter Roberson
2020-3-2
We discourage people from offering complete solutions to homework assignments.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!