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!