product of a series
조회 수: 5 (최근 30일)
이전 댓글 표시
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
채택된 답변
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
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개)
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!