matlab for循环内部不独立,如第i时刻的数据受到i-1时刻数据的影响
示例:
tempL = zeros(4, 5);
tempL(1, :) = ones(1, 5);
a = [1:6;
1, 4, 2, 7, 1, 0;
2, 2, 9, 7, 2, 1];
for i = 1:size(a, 1)
tempL(i+1, :) = tempL(i, :) + a(i, 2:end) - a(i, 1:end-1);
end
每次迭代时,tempL的第i+1行是tempL的第i行和a的第i行之间的差值相加的结果。
可以发现,
tempL(2, : ) = tempL(1, : ) + a的第1行差值
tempL(3, : ) = tempL(2, : ) + a的第2行差值 = tempL(1, : ) + a的第1行差值 + a的第2行差值
tempL(4, : ) = tempL(3, : ) + a的第3行差值 = tempL(1, : ) + a的第1行差值 + a的第2行差值 + a的第3行差值
以此类推……
或许可以用matlab中的 cumsum 函数来对差值求累加和,如下所示:
tempL = zeros(4, 5);
tempL(1, :) = ones(1, 5);
a = [1:6;
1, 4, 2, 7, 1, 0;
2, 2, 9, 7, 2, 1];
repmat_temp = repmat(tempL(1,:), 3, 1);
diff_values = diff(a, 1, 2); % 计算a中相邻元素之间的差值
cumsum_value = cumsum(diff_values, 1);
tempL(2:end, :) = repmat_temp+cumsum_value; % 累积求和并加到tempL中
两种代码得到的结果一致。
不妨简单测试一下两种代码的运行时间差距
(由于试验代码比较简单,循环100000次比较效果)
对于第一种 for 循环写法,耗时0.389780 秒,
对于第二种向量化写法,耗时0.137272 秒。
时间缩短一半以上,大功告成!