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

时间:2015-03-30 02:18:03

标签: 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

我很难对这段代码进行矢量化,任何帮助都会受到赞赏。

1 个答案:

答案 0 :(得分:2)

你可以分两个阶段完成它,一个用于原始代码的每个循环。但由于第二个循环中的数据依赖性,您需要将第二个循环进一步分为两个阶段,因此具有对应于这三个阶段的矢量化代码。这是最后的实施 -

%// 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;