如何矢量化 for 循环但其中包含条件?(主要在Matlab中)
一个 for 循环,其中要根据二进制值(0 或 1)** 选择要乘以 ** 的矩阵,然后将其与另一个矩阵相乘以计算每次迭代都会更新的累积 Product。既然我有1亿点,那么很快就可以做到这一点。如果可能的话,矢量化将有很大帮助。
[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 )
提前致谢。