## Minimize Redundant Operations in Loops

This example shows how to minimize redundant operations in loops. When a loop operation does not depend on the loop index, performing it inside a loop is redundant. This redundancy often goes unnoticed when you are performing multiple operations in a single MATLAB® statement inside a loop. For example, in the following code, the inverse of the matrix `B` is being calculated 100 times inside the loop although it does not depend on the loop index:

```for i=1:100 C=C + inv(B)*A^i*B; end ```

Performing such redundant loop operations can lead to unnecessary processing. To avoid unnecessary processing, move operations outside loops as long as they do not depend on the loop index.

1. Define a function, `SeriesFunc(A,B,n)`, that calculates the sum of `n` terms in the following power series expansion:

`$C=1+{B}^{-1}AB+{B}^{-1}{A}^{2}B+...$`
``` function C=SeriesFunc(A,B,n) % Initialize C with a matrix having same dimensions as A C=zeros(size(A)); % Perform the series sum for i=1:n C=C+inv(B)*A^i*B; end ```
2. Generate code for `SeriesFunc` with 4-by-4 matrices passed as input arguments for `A` and `B`:

```X = coder.typeof(zeros(4)); codegen -config:lib -launchreport SeriesFunc -args {X,X,10}```

In the generated code, the inversion of `B` is performed `n` times inside the loop. It is more economical to perform the inversion operation once outside the loop because it does not depend on the loop index.

3. Modify `SeriesFunc` as follows:

``` function C=SeriesFunc(A,B,n) % Initialize C with a matrix having same dimensions as A C=zeros(size(A)); % Perform the inversion outside the loop inv_B=inv(B); % Perform the series sum for i=1:n C=C+inv_B*A^i*B; end ```

This procedure performs the inversion of `B` only once, leading to faster execution of the generated code.

## Support 평가판 신청