【问题标题】:Vectorization of FOR loopFOR循环的向量化
【发布时间】:2019-07-09 00:31:15
【问题描述】:

感谢用户 carandraug,我知道 gallery ("circul",y) 有没有办法对这个 FOR 循环进行矢量化 但这只会将单元格转移到下一个相邻的单元格,我也尝试过 toeplitz 但没有奏效)。

我正在尝试使用 circshift 和变量 shift_over 在示例代码中调整班次。

变量 y_new 是我试图获得的输出,但不必在示例中使用 FOR 循环(这个 FOR 循环可以向量化吗)。

请注意:此示例中使用的数字只是一个示例,实际数组将是语音/音频 30-60 秒信号(因此 y_new 数组可能很大)并且不会t 是像 1,2,3,4,5 这样的连续数字。

tic
y=[1:5];
[rw col]= size(y); %get size to create zero'd array
y_new= zeros(max(rw,col),max(rw,col)); %zero fill new array for speed

shift_over=-2; %cell amount to shift over

for aa=1:length(y)
  if aa==1
    y_new(aa,:)=y; %starts with original array
  else  
    y_new(aa,:)=circshift(y,[1,(aa-1)*shift_over]); %
  endif
end
y_new

fprintf('\nfinally Done-elapsed time -%4.4fsec- or -%4.4fmins- or -%4.4fhours-\n',toc,toc/60,toc/3600);


y_new =

           1           2           3           4           5
           3           4           5           1           2
           5           1           2           3           4
           2           3           4           5           1
           4           5           1           2           3

Ps:我使用的是 Octave 4.2.2 Ubuntu 18.04 64bit。

【问题讨论】:

  • 总是很难弄清楚你到底想做什么。我必须一遍又一遍地阅读问题,然后分析现有的sn-p。我认为您的问题会得到更多关注,因为首先找出您想做什么会更容易。顺便说一句,你读过xyproblem.info 吗?
  • @Andy 很抱歉,我确实尝试完全解释它,我包含代码示例。除了输出y_new,我正在尝试获取,并附上我正在尝试执行的操作。 Please note: The numbers that are used in this example are just an example the real array will be voice/audio 30-60 second signals (so the y_new array could be large) and won't be sequential numbers like 1,2,3,4,5。 (也许我包含了很多信息)我不确定我该怎么说如何更直接地矢量化 FOR 循环。我确实将它包含在第一行和标题中。
  • 我猜你还没有读到 XY 问题,对吧?
  • @RickT 我认为问题是,你为什么需要y_new?生成它后你打算用它做什么?是否可以在不创建可能庞大的信号矩阵的情况下处理您的数据?
  • @Andy 是的,我确实读过它,我真的明白你的意思,问题是我正在以多种方式试验音频信号。当一个实验不起作用时,我会重新研究理论并尝试不同的方法。

标签: vectorization octave


【解决方案1】:

我很确定这是一个经典的 XY 问题,您想要计算一些东西,并且您认为构建一个冗余的 n x n 矩阵是个好主意,其中 n 是您的音频文件在样本中的长度。也许你想玩自相关但这里的关键点是我怀疑构建请求的矩阵是一个好主意但是你去吧:

您的代码:

y = rand (1, 3e3);
shift_over = -2;

clear -x y shift_over
tic
[rw col]= size(y); %get size to create zero'd array
y_new= zeros(max(rw,col),max(rw,col)); %zero fill new array for speed

for aa=1:length(y)
  if aa==1
    y_new(aa,:)=y; %starts with original array
  else  
    y_new(aa,:)=circshift(y,[1,(aa-1)*shift_over]); %
  endif
end
toc

我的代码:

clear -x y shift_over
tic
n = numel (y);
y2 = y (mod ((0:n-1) - shift_over * (0:n-1).', n) + 1);
toc

给我的系统:

Elapsed time is 1.00379 seconds.
Elapsed time is 0.155854 seconds.

【讨论】:

    猜你喜欢
    • 2019-05-17
    • 1970-01-01
    • 2021-06-27
    • 2013-07-21
    • 1970-01-01
    • 1970-01-01
    • 2014-03-15
    相关资源
    最近更新 更多