Vectorize 3 for loops
1 view (last 30 days)
Show older comments
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 Comments
Jan
on 24 Aug 2012
The expression is not complete:
DiagVek(k,n)-(prod((X2(n,:) ??? X1(k,:)).^ PermPolynom(l,:)));
What does appear instead of the ???
Accepted Answer
Daniel Shub
on 24 Aug 2012
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 Comments
Daniel Shub
on 24 Aug 2012
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.
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!