Vectorize 3 for loops
2 ビュー (過去 30 日間)
古いコメントを表示
Hello,
I have to do a large calculation and right now I use 3 for loops to do it....but I wonder if I could use vectorization to make it faster.
my code:
PermPolynom = allVL1(dim,2,'==',inf);
lenghtPermPolynom = size(PermPolDiag,1);
for n = 1:lenght_X2
for k = 1:lenght_X1
for l = 1:lengthPermPolynom
DiagVek(k,n) = DiagVek(k,n)-(prod((X2(n,:) X1(k,:)).^ PermPolynom(l,:)));
end
end
end
X1 and X2 are matrices with different number of rows but same number of columns (every row stands for a multidimensional vector of length dim).
For example:
X1 = [0 2 3 2 3; 2 3 4 1 3; 3 4 5 4 3;.....;4 5 2 1 2] -> dim = 5
PermPolynom gives me all possible Permutations for a vector of length dim so that the sum of all entries in the vector is 2.
example for dim 3 and sum = 1:
[0 0 1; 0 1 0; 1 0 0]
The goal is to calculate for every entry in X1 and X2 the multidimensional polynomial.
I tried to vectorize it like it is said in a help of matlab:
i = 0;
for t = 0:.01:10
i = i + 1;
y(i) = sin(t);
end
A vectorized version of the same code is
t = 0:.01:10;
y = sin(t);
but that doesn't work...I think because of the different length of X1 and X2.
Is there a way to get rid of the loops?
Thanks Tim
2 件のコメント
Jan
2012 年 8 月 24 日
The expression is not complete:
DiagVek(k,n)-(prod((X2(n,:) ??? X1(k,:)).^ PermPolynom(l,:)));
What does appear instead of the ???
採用された回答
Daniel Shub
2012 年 8 月 24 日
Loops are no longer painfully slow in MATLAB and haven't been for quite some time. A better question would be how can I speed up my code. For this we need more than just the code, we also need details about the dataset (how big is it). Have you run your code through mlint and the profiler?
It doesn't look like you have preallocated DiagVek. While there have been improvements in MATLAB's dynamic memory allocation, preallocation still tends to be very important.
2 件のコメント
Daniel Shub
2012 年 8 月 24 日
That mlint warning is key and despite needing the matrix to be a different size every iteration, suggests you are doing something wrong. You should take a look at cell arrays and/or consider simply overwriting the matrix on every iteration instead of saving all the different size matrices.
その他の回答 (0 件)
参考
カテゴリ
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!