[英]Matlab matrix operations without loops
I have an issue with a code performing some array operations. 我对执行一些数组操作的代码有问题。 It is getting too slow, because I am using loops.
它变得太慢了,因为我正在使用循环。 I am trying for some time to optimize this code and to re-write it with less or without loops.
我正在尝试一段时间来优化此代码,并以更少或没有循环的方式对其进行重新编写。 Until now unsuccessfully.
直到现在都没有成功。 Can you please help me solve this:
您能帮我解决这个问题吗?
YVal = 1:1:100000;
M_MAX = 1000;
N_MAX = 2000;
clear YTemp
tic
for M=1:1:M_MAX
for N = 1:1:N_MAX
YTemp(M,N) = sum(YVal (N+1:N+M) ) - sum(YVal (1:M) );
end
end
For large N_MAX
and M_MAX
the execution time of these two loops is very high. 对于较大的
N_MAX
和M_MAX
,这两个循环的执行时间非常长。 How can I optimize this? 我该如何优化呢?
Thank you! 谢谢!
Assuming YVal
is larger than N_MAX+M_MAX
假设
YVal
大于N_MAX+M_MAX
sum1 = cumsum( YVal(1:(M_MAX+N_MAX)) ); % sum1(M) = sum(YVal(1:M))
If I'm not mistaken, then 如果我没记错的话
sum( YVal( N+1:N+M ) ) = sum1( N + M ) - sum1( N )
And therefore 因此
YTemp( M, N ) = sum1( N + M ) - sum1( N ) - sum1( M )
[M N] = ndgrid( 1:M_MAX, 1:N_MAX );
YTemp = sum1( N + M ) - sum1( N ) - sum1( M );
Have I got it right? 我说对了吗?
EDIT: 编辑:
Another go without ndgrid
没有
ndgrid
另一ndgrid
sum1 = cumsum( YVal( 1 : (N_MAX+M_MAX) ) );
YTemp = bsxfun( @minus, ...
bsxfun( @minus, ...
sum1( bsxfun( @plus, 1:N_MAX, (1:M_MAX)' ) ) , sum1 ),...
sum1' );
You should be able to speed it up a little by hoisting the invariant term out of the inner loop, eg 通过将不变项提升到内循环之外,您应该能够稍微加快速度,例如
for M=1:1:M_MAX
sum2 = sum(YVal(1:M));
for N = 1:1:N_MAX
YTemp(M,N) = sum(YVal(N+1:N+M)) - sum2;
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.