product of a series
5 views (last 30 days)
Show older comments
Hi,
how should I write this production in matlab?
p(k)=(m1−m2)*(m2−m3)*,...*,(mN−2−mN−1)*(m99−m100), where k from 1 to 100.
thx
0 Comments
Accepted Answer
Star Strider
on 21 Dec 2019
Edited: Star Strider
on 21 Dec 2019
Numerically:
m = rand(1, 100);
m = rand(1, 100); % Row Vector
rm = reshape(m, 2, []);
p = prod(diff(rm,[],1)) % Desired Result
EDIT — (21 Dec 2019 at 15:46)
Alternatively:
p = prod(-diff(rm,[],1)) % Desired Result
in the event that the first row was supposed to be subtracted from the second, instead of the second being subtracted from the first.
1 Comment
Marco Riani
on 21 Dec 2019
I think the solution Star provided (given a vector or 2n elements) computes
(x(2)-x(1))*((x(4)-x(3))*...*(x(2n)-x(2n-1))
For example suppose x is
x=[1 5 6 11 12 4] % Row Vector
rm = reshape(x, 2, []); gives
rm =
1 6 12
5 11 4
and
diff(rm,[],1)
ans =
4 5 -8
and the solution given by Star is the product of (x(2)-x(1))*((x(4)-x(3))*...*(x(2n)-x(2n-1))
Furthermore reshape(x, 2, []) assumes that x has a number of elements which is even.
In order to obtain
(x(1)-x(2))*((x(2)-x(3))*...*(x(n-1)-x(n))
assuming x is a row vector the correct solution (if I am not mistaken) is
prod(diff(fliplr(x)))
In the example above, if x=[1 5 6 11 12 4]
fliplr(x) is
4 12 11 6 5 1
diff(fliplr(x)) is
8 -1 -5 -1 -4
(x(n-1)-x(n))* .... ((x(2)-x(3))*(x(1)-x(2))*
Of course if x is a column vector, it is enough to replace fliplr with flipud.
The code is given below
x=[1 5 6 11 12 4]; % Row Vector
rm = reshape(x, 2, []);
% Solution given by Star
prod(diff(rm,[],1))
% New solution in presence of a row vector
prod(diff(fliplr(x)))
% New solution in presece of a column vector
x=[1 5 6 11 12 4]'; % Column Vector
prod(diff(flipud(x)))
More Answers (0)
See Also
Categories
Find more on Elementary Math in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!