How to write a semifactorial function that iterates up to the input?

조회 수: 1 (최근 30일)
Aaron Grubbs
Aaron Grubbs 2017년 10월 7일
편집: Cedric 2017년 10월 7일
Hello all,
I'm currently trying to write a function that calculates the semifactorial of an input statement whether it's odd or even, but I can't figure out how to make it iterate to the input statement.
The definition:
The semifactorial of n is the product of the integers between 1 and n which have the same parity (even or odd) as n. For example, 7‼ = 1 × 3 × 5 × 7 = 105, and 8‼ = 2 × 4 × 6 × 8 = 384.
Here's my code so far:
function [ factorial ] = FactorialPi( num )
i = 0;
factorial = [];
for i = 0:2:num
if mod(num, 2) ~= 0
num = (2 * i) + 1;
%else mod(num, 2) == 0
% i = (2 * i);
factorial = [factorial;num]
end
end
My output when I call FactorialPi(7) is:
factorial =
1
factorial =
1
5
factorial =
1
5
9
factorial =
1
5
9
13
ans =
1
5
9
13
Any help would be greatly appreciated, thank you!
The semifactorial of

답변 (1개)

Cedric
Cedric 2017년 10월 7일
편집: Cedric 2017년 10월 7일
This is a good start as you are trying, as a first step, to operate a bit how you would proceed by hand, element by element in a loop.
The next step is to realize that MATLAB can operate on arrays:
>> x = 1 : 3 : 11
x =
1 4 7 10
defines a row vector, it is actually how you define the pool of values that your loop variable must take through iterations. Now say you have a vector of values, would you be able to compute their product without using a loop? You probably saw the function SUM, maybe there is an equivalent for products? [-> Google or Doc]
Here is an element-wise square and a sum to illustrate usual operations with arrays:
>> x.^2 % Element-wise square.
ans =
1 16 49 100
>> sum( x ) % Sum of all elements.
ans =
22
Once you understand this you'll know two things: how to build vectors of linearly spaced elements from a lower bound to an upper bound, and how to compute their product.
You will be in a situation where you know how to define the upper bound as it is the input of the function, but you will have to find a way to define the lower bound, which is a number that is either 1 or 2 depending the parity of the input. Maybe there is a way .. maybe you almost found it already (!)

카테고리

Help CenterFile Exchange에서 Special Functions에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by