问题描述
我有一个巨大的矩阵.我只是给出了一个尺寸为(1*1000000).
I have a huge matrix. I am just given an example of a matrix with size (1*1000000).
我正在使用简单的Loop
(我不喜欢使用Loop
)来找到k
.
I am using simple Loop
( I do not prefer using Loop
) to find k
. where
k= k(ii)=(abs(a(ii+1)-2*a(ii)+a(ii-1)))/(a(ii+1)+2*a(ii)+a(ii-1))
但是,对于较小的矩阵,这很好.如果我有大量数据,那将需要很长时间.有什么方法可以使用向量代替Loop
来找到k
?
However, this is fine with small matrices. If I have huge data that will take a long time. Is there any way to use vector instead of Loop
to find k
?
clear;
clc;
a=rand(1,1000000);
for ii=2:size(a,2)-1
k(ii)=(abs(a(ii+1)-2*a(ii)+a(ii-1)))/(a(ii+1)+2*a(ii)+a(ii-1));
end
推荐答案
如果要对其向量化,则需要知道每次迭代将使用哪个a
索引.例如,术语a(ii+1)
的ii
从2
迭代到999999
意味着您正在使用a
的元素从索引3到最后,并且类似地发现了其他术语.然后只需元素明智的划分./
. 0
是在开始时手动添加的,因为在您的代码中,您没有在第一个索引处显式存储任何内容,而跳过索引时将自动存储的内容为零.
If you want to vectorise it, you need to know which indices of a
you would be using at each iteration. For example, The term a(ii+1)
with ii
iterating from 2
to 999999
means you're using the elements of a
from indices 3 to last and similarly find that out for other terms. Then just do the element wise division ./
. 0
is manually appended at the start since in your code, you didn't explicitly store anything at first index and zero is what automatically gets stored when you skip an index.
k = [0 abs(a(3:end)-2*a(2:end-1)+a(1:end-2)) ./ (a(3:end)+2*a(2:end-1)+a(1:end-2))];
在具有R2017a的系统上,使用 timeit
计时的性能和a=rand(1,1e8);
:
Orig_Post = 14.3219
Orig_Post_with_Preallocation = 1.7764
Vectorised = 5.3292
因此可以看出,新版本中的循环已得到显着改善.事实证明,对于k
,使用具有适当预分配内存的循环的解决方案比矢量化解决方案要快得多.您遇到的性能下降是由于没有预分配 preallocation (作为 Cris Luengo 已经).要预分配,请写k = zeros(1, size(a,2)-1);
在循环之前.
So it can be seen that loops have been significantly improved in the newer versions. It turns out that the solution with the loop with properly pre-allocated memory for k
is much faster than the vectorised one. The reduced performance you're experiencing is caused due to no preallocation (as Cris Luengo already suggested). To pre-allocate, write k = zeros(1, size(a,2)-1);
before the loop.
这篇关于使用向量代替循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!