1 view (last 30 days)

Show older comments

Hi,

Is there any chance that the following code could be optimized? The matrices are not sparse. I wonder whether the fact that the matrix A doesn't change might make it possible to pre-calculate an expression before the loop to avoid the double multiplication in this A*V*A' term.

Notes :

Since B is symmetric, V will be symmetric, too.

The matrix A can be rank-deficient and therefore V will also be rank-deficient.

Thank you!

T = 500;

N = 1200;

Vt = zeros(N,N,T);

B = randn(N,N);

B = (B+B')/2;

A = randn(N,N);

for t = 1:T

Vt(:,:,t+1) = A*Vt(:,:,t)*A'+B;

end

Jan
on 12 May 2021

No, there is no chance for a significant speedup or vectorization, because the result of the former iteration is the input of the current one. One tiny improvement is to pre-allocate Vt to the exact matching size:

Vt = zeros(N, N, T + 1);

% ^^^

James Tursa
on 17 May 2021

Edited: James Tursa
on 17 May 2021

@Tintin Milou MATLAB variables do not have a "symmetric" attribute flag that I know of. Just because you create a variable that is symmetic with an expression such as (A+A') doesn't mean that MATLAB will necessarily know downstream that the matrix is symmetric. To MATLAB this result is simply just another matrix, and any subsequent operation downstream that depended on symmetry would have to check all the elements. Some functions will do this check but others will not.

There are certain matrix multiplication expressions that MATLAB can recognize where the result will necessarily be symmetric, and in those cases MATLAB can call symmetric BLAS routines in the background to speed up calculations and obtain an exact symmetric result. E.g.,

A = an arbitrary real matrix

C = A' * A is recognized by MATLAB as being symmetric and it will call a symmetric BLAS routine in the background.

The C result will take less time and the result is guaranteed to be exactly symmetric.

B = A'

D = B * A is not recognized by MATLAB as being symmetric, so a generic BLAS routine will be used.

The D result will take more time and the result is not guaranteed to be exactly symmetric. MATLAB doesn't keep track of where B came from and doesn't know it is exactly the transpose of A, so it doesn't do any symmetric optimizations for the operation.

And for the different expression A * B * A' where B is symmetric, MATLAB does not check that B is symmetric so it doesn't know that the result will be symmetric. There are no symmetric optimizations taken for this case, and generic matrix multiplies are done instead with the result not guaranteed to be exactly symmetric because of floating point arithmetic effects.

James Tursa
on 18 May 2021

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!