product of a series

6 次查看(过去 30 天)
Ajira
Ajira 2019-12-21
编辑: Star Strider 2019-12-21
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

采纳的回答

Star Strider
Star Strider 2019-12-21
编辑:Star Strider 2019-12-21
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 个评论
Marco Riani
Marco Riani 2019-12-21
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)))

请先登录,再进行评论。

更多回答(0 个)

类别

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

Community Treasure Hunt

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

Start Hunting!

Translated by