matlab:循环的棘手矢量化,其中第 n 个值取决于第 n 个和第 n+k 个值

标签 matlab vectorization bsxfun

这是一个 matlab 程序的循环版本,适用于 55 个值的数组,棘手的部分是第 n 个值是从第 n 个和 (n+31)-st 更新的,并且在第二种情况,它是 (n-24)-th。

oldval = rand(1,55);

for j1 = 0:23
    new_random = oldval(j1 + 1) - oldval(j1 + 31 + 1);
    if (new_random < 0.0)
        new_random = new_random + 1.0 ;
    end
    oldval(j1 + 1) = new_random ;
end

for j1 = 24:54
    new_random = oldval(j1 + 1) - oldval((j1 - 24) + 1);
    if (new_random < 0.0)
        new_random = new_random + 1.0 ;
    end
    oldval(j1 + 1) = new_random ;
end

我很难对这段代码进行矢量化,我们将不胜感激。

最佳答案

您可以分两个阶段完成,一个用于原始代码的每个循环。但是由于第二个循环中的数据依赖性,您需要将第二个循环进一步分为两个阶段,从而获得与这三个阶段相对应的矢量化代码。这是最终的实现 -

%// Initialize a new array with a copy of the input array
oldval_vect = oldval;

%// Vectorize the first loop that sets the elements 1 to 24
loop1_diff = oldval(1:24) - oldval(32:55);
loop1_add = double(loop1_diff<0) + loop1_diff;
oldval_vect(1:24) = loop1_add;

%// Vectorize the second loop for setting the rest of the elements.
%// Now, within the second loop, there is data dependency after the first 
%// 24 elements of the input array are accessed, so we need to break this 
%// second loop into two parts, one that sets elements from 25 till 48 and 
%// the next one that does from 49 till 55.
loop2_part1_diff = oldval_vect(25:48) - oldval_vect(1:24);
loop2_part1_add = double(loop2_part1_diff<0) + loop2_part1_diff;
oldval_vect(25:48) = loop2_part1_add;

loop2_part2_diff = oldval_vect(49:55) - oldval_vect(25:31);
loop2_part2_add = double(loop2_part2_diff<0) + loop2_part2_diff;
oldval_vect(49:55) = loop2_part2_add;

关于matlab:循环的棘手矢量化,其中第 n 个值取决于第 n 个和第 n+k 个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29337424/

相关文章:

Matlab bsxfun() 代码

matlab - 根据索引列表从数组中提取固定数量的数据

matlab - 我怎样才能加快在 Matlab 中调用分位数的速度?

string - 如何在Matlab中将字符串变量转换为 boolean 值?

matlab - 如何创建对称零和一矩阵

matlab 绘图图像作为图形的背景

c++ - 为什么向量化失败?

python - Haversine 距离的最小值的有效计算

matlab - 丹尼尔森函数

arrays - 通过在元胞数组中存储为向量的索引对向量的子集求和