使用向量代替循环 [英] Using vector instead of Loop

查看:142
本文介绍了使用向量代替循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个巨大的矩阵.我只是给出了一个尺寸为(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)ii2迭代到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 已经

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.

这篇关于使用向量代替循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆