フィルターのクリア

How to make a function operate on a vector of arbitrary length

1 回表示 (過去 30 日間)
JJH
JJH 2018 年 11 月 2 日
回答済み: Stephan 2018 年 11 月 2 日
I have written a function to compute the factorial of a positive integer and return error results if something that isn't a positive integer is input into the function. However, I need to extend this so that the function can be applied to a vector of any length and will find the factorial of each element individually. How do I go about doing this?
function s = sfactorial(x)
if x < 0
error('x must be positive')
elseif floor(x) ~= x
error('x must be an integer')
else
result=1;
for i = 1:x
result=result*i;
end
end
result

採用された回答

Stephan
Stephan 2018 年 11 月 2 日
function s = sfactorial(x)
if x < 0
error('x must be positive')
elseif floor(x) ~= x
error('x must be an integer')
else
result=ones(1,numel(x));
for k = 1:numel(x)
for i = 1:x(k)
result(k) = result(k)*i
end
end
end
s = result;
end

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by