How to avoid the for loops?
8 ビュー (過去 30 日間)
古いコメントを表示
I want to make the following code faster by avoiding the two for loops (if possible). I tried to make a vector multiplication .* operator which is not working here.
Since, the arguments / variables (Order, X and Y) are small, the Y_grid cell array can be calculated so fast here in the given script. However, I would like to make it as a function for later use. (So that, I can input different and higher arguments). Then the two for loops would make the programme so slow.
Inside the loops, there is a function too - (matFunction.m)*, is a small function here which needs varying input arguments. I don't want to make any change in this function.
Please have a look and suggest me some ideas! Many thanks in advance******
Order = 5;
X = 0:3;
Y = 0:5;
Y_grid {length(Y), length(X)}=zeros; % Initialization of cell array by zeros.
tic
for i=1:length(X)
for j=1:length(Y)
Y_grid{j,i}= matFunction( Order,Y(j),X(i) );
end
end
toc
(The matFunction.m* is given below. ):
function [ Mat ] = matFunction( Order , Y , X )
Mat=[0:1:Order]*X*Y;
Mat=repmat(Mat,Order,Order);
end
0 件のコメント
回答 (1 件)
Stephen23
2015 年 10 月 25 日
編集済み: Stephen23
2015 年 10 月 25 日
Here is a solution using matrix multiplication and one bsxfun call:
Order = 5;
X = 0:3;
Y = 0:5;
A = ones(Order,1)*(0:Order);
B = bsxfun(@times,A,reshape(Y(:)*X,1,1,[],numel(X)));
C = squeeze(num2cell(repmat(B,1,Order),[1,2]));
Under some circumstances this code is faster than the nested loops and separate function, but this depends on factors such as the matrix sizes, etc. With the values you give it is around 1/3 to 1/2 faster:
Elapsed time is 0.002530 seconds. % nested loops + function
Elapsed time is 0.001254 seconds. % matrix + bsxfun
To really make the code faster I would avoid cell arrays entirely, and just stick to using the dimensions of the numeric array. This makes writing vectorized code much more intuitive and easier.
2 件のコメント
Stephen23
2015 年 10 月 26 日
Interesting task... and not an easy question for us to answer. The first question: is it worth trying to optimize the code? If it takes a few hours of re-coding in order to save ten minutes of computation, then is this a good use of time? How much faster do you expect the code to be able to run?
One way that you might be able to speed it up is to consider removing any operations from inside the loops that are always the same or that are applied to the entire output of the loops, and placing these before/after the loops. In other words: pre-compute everything possible before the loops. This would be quite a fundamental change in how the code works, and might make it less intuitive to follow.
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!