Pages

1.3.14

Smart way to write "trace" command in Matlab - Boost your code, save time

Sometimes is necessary to write complex operations in Matlab involving matrices. These operations can be of different type and they operate in different ways.

Today I'll show you how write in a smart way the "trace" command of a matrix or a product/sum/difference of the using matrices notation to speed up your code.



What is the trace command? Well, read here

As you read in the Wiki above, a trace will sum all the diagonal elements of a given matrix.

So for a give matrix A holds that:

This operation in Matlab is done through the command "trace( )" where between parenthesis you must pass the matrix for which you want to obtain the trace.

In a complex program it could happend to call a high number of times this command and it's time expensive specially if applied to matrices of big dimensions.

Tip 1: Get the trace of a given matrix A

To speed up the computation of a matrix you can apply this command:

sum(diag(A))

which means: sum the elements of the vector which results from the extraction of the diagonal elements of A.

If you have different matrices you can put them togheter inside a bigger one (see blkdiag) and apply this command.

Tip 2: Get the trace of a product of matrices AB

This is a very usefull tip;

you can rewrite trace(A*B) as

Suppose that A and B are two sqare matrices of dimension m x m.

reshape(A',1,m*m) * reshape(B,m*m,1)

Applying these tricks to complex Matlab programs will save your time!

Enjoy



No comments:

Post a Comment