0

How to vectorize a for loop but with conditionals in it ? (mainly in Matlab)

A for-loop in which a matrix to multiply ** is chosen based on a binary value ( 0 or 1) ** that is then multiplied with another matrix to calculate a cumulative Product that gets updated with every iteration. Since I have 100 million points, it would be good to do this very fast. Vectorization, if possible will help a lot.

[sizMat1 sizMat2] = size(matrixToMultiply); cumulMatProduct = ones(sizMat1,1); %stores the cumulative Products of chosen Matrices. %gets updated at every iteration for ix = 2:length(col1) % Depending on if the value is either 0 or 1, pick a matrix; if (col1(ix) == 0 ) cumulProduct = simpleMatrix0 * cumulMatrixProduct; matrixToMultiply = matrix1; elseif (col1(ix) == 1 ) matrixToMultiply = matrix2; end anotherMatrixtoMultiply = diag( exp(constantMatrix) * col2(ix) ); % Another Matrix is created by multiplying a scalar %(picked from the same index ix of a different column col2 having same dimensions as col1) cumulMatrixProduct = matrixToMultiply*anotherMatrixtoMultiply*cumulMatrixProduct; end % matrixToMultiply is 101 x 101 % constantMatrix is 101 by 1 % anotherMatrixtoMultiply is 101 by 101 % cumulMatrixProduct = 101 x 1 (Result ) 

Thanks in advance.

1 Answer 1

1

Your problem here isn't so much the condition, but the fact that you have a data dependency between iterations of the loop. That prevents parallel processing, including naive vectorization. For example, the prod function won't help you because it performs element products (parallelizable!) per row, and not matrix multiplies.

One thing I do notice is that the col2(ix) are all scalars and can be removed from the loop. Then you'd multiply by prod(col2(2:length(col1))) at the end, and anotherMatrixToMultiply wouldn't change each iteration. You can't move that outside the loop, however, because matrix multiplication is not commutative (even when it is according to the rules of linear algebra, changing order of floating point operations may change the accumulated error).

Sign up to request clarification or add additional context in comments.

1 Comment

Yes. that's something I've done already ( moving the calculation to create anotherMatrixToMultiply outside) This dependency is bad (& any such task is not easily parallelized for sure, but would like to know if there could be any super linear algebra trick for help in this case!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.