计算数组中接下来n个元素的乘积 [英] Compute the product of the next n elements in array
问题描述
我想计算矩阵的下一个n
个相邻元素的乘积.要相乘的元素的数量n
应该在函数的输入中给出.
例如,对于此输入,我应该从第一个元素开始计算每三个连续元素的乘积.
I would like to compute the product of the next n
adjacent elements of a matrix. The number n
of elements to be multiplied should be given in function's input.
For example for this input I should compute the product of every 3 consecutive elements, starting from the first.
[p, ind] = max_product([1 2 2 1 3 1],3);
这给出了[1*2*2, 2*2*1, 2*1*3, 1*3*1] = [4,4,6,3]
.
有什么可行的方法吗?现在,我使用以下方法进行操作:
Is there any practical way to do it? Now I do this using:
for ii = 1:(length(v)-2)
p = prod(v(ii:ii+n-1));
end
其中v
是输入向量,n
是要相乘的元素数.
where v
is the input vector and n
is the number of elements to be multiplied.
在此示例中为n=3
,但可以采用任何正整数值.
in this example n=3
but can take any positive integer value.
根据n
是奇数还是偶数还是length(v)
是奇数还是偶数,我有时会得到正确的答案,但有时会出错.
例如参数:
Depending whether n
is odd or even or length(v)
is odd or even, I get sometimes right answers but sometimes an error.
For example for arguments:
v = [1.35912281237829 -0.958120385352704 -0.553335935098461 1.44601450110386 1.43760259196739 0.0266423803393867 0.417039432979809 1.14033971399183 -0.418125096873537 -1.99362640306847 -0.589833539347417 -0.218969651537063 1.49863539349242 0.338844452879616 1.34169199365703 0.181185490389383 0.102817336496793 0.104835620599133 -2.70026800170358 1.46129128974515 0.64413523430416 0.921962619821458 0.568712984110933]
n = 7
我得到了错误:
Index exceeds matrix dimensions.
Error in max_product (line 6)
p = prod(v(ii:ii+n-1));
有什么正确的一般方法吗?
Is there any correct general way to do it?
推荐答案
更新
灵感来自好想的 Dev-iL的答案 ,它提供了这个方便的解决方案,该解决方案不需要 Matlab R2016a或更高版本:
out = real( exp(conv(log(a),ones(1,n),'valid')) )
基本思想是将乘法转换为总和,然后可以使用移动平均值,而移动平均值又可以通过
The basic idea is to transform the multiplication to a sum and a moving average can be used, which in turn can be realised by conv
olution.
这是使用> gallery
以获得循环矩阵,并在乘以元素之前索引所得矩阵的相关部分:
This is one way using gallery
to get a circulant matrix and indexing the relevant part of the resulting matrix before multiplying the elements:
a = [1 2 2 1 3 1]
n = 3
%// circulant matrix
tmp = gallery('circul', a(:))
%// product of relevant parts of matrix
out = prod(tmp(end-n+1:-1:1, end-n+1:end), 2)
out =
4
4
6
3
更有效的内存替代方法如果输入中没有零:
a = [10 9 8 7 6 5 4 3 2 1]
n = 2
%// cumulative product
x = [1 cumprod(a)]
%// shifted by n and divided by itself
y = circshift( x,[0 -n] )./x
%// remove last elements
out = y(1:end-n)
out =
90 72 56 42 30 20 12 6 2
这篇关于计算数组中接下来n个元素的乘积的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!