# Documentation

## Common Errors and Warnings

### fi*non-fi Errors

Original Algorithm New Algorithm
```function y = myProduct(x) y = 1; for n = 1:length(x) y(:) = y*x(n); end end```

Issue:

When multiplying a fixed-point variable by a non-fixed-point variable, the variable that does not have a fixed-point type can only be a constant.

Fix:

Before instrumenting your code, cast the non-fi variable to an acceptable fixed-point type.

```function y = myProduct(x) y = ones(1,1, 'like', x(1)*x(1)); for n = 1:length(x) y(:) = y*x(n); end end```

### Data Type Mismatch Errors

Original AlgorithmNew Algorithm
Function:
```function y = mysum(x,T) %#codegen y = zeros(size(x), 'like', T.y); for n = 1:length(x) y = y + x(n); end end```

Issue:

y uses the default `fimath` setting `FullPrecision` for the `SumMode` property. At each iteration of the for-loop in the function `mysum`, the word length of y grows by one bit. During simulation in MATLAB®, there is no issue because data types can easily change in MATLAB. However, a type mismatch error occurs at build time because data types must remain static in C.

Fix:

Rewrite the function to use subscripted assignment within the for-loop.

By rewriting y = y + x(n) as y(:) = y + x(n), the value on the right is assigned in to the data type of y. This assignment preserves the `numerictype` of y and avoids the type mismatch error.

Function:
```function y = mysum(x,T) %#codegen y = zeros(size(x), 'like', T.y); for n = 1:length(x) y(:) = y + x(n); end end```
Types Table:
```function T = mytypes(dt) switch(dt) case 'fixed' F = fimath('RoundingMethod', 'Floor') T.x = fi([],1,16,11, F); T.y = fi([],1,16,6, F); end end```
Types Table:
```function T = mytypes(dt) switch(dt) case 'fixed' F = fimath('RoundingMethod', 'Floor') T.x = fi([],1,16,11, F); T.y = fi([],1,16,6, F); end end```

### Mismatched fimath Errors

Original Algorithm New Algorithm
Function:
```function y = mysum(x,T) %#codegen y = zeros(size(x), 'like', T.y); for n = 1:length(x) y(:) = y + x(n); end end```

Issue:

If two `fi` object operands have an attached `fimath`, the `fimaths` must be equal.

Fix:

Use the `removefimath` function to remove the `fimath` of one of the variables in just one instance. By removing the `fimath`, you avoid the "mismatched `fimath`" error without permanently changing the `fimath` of the variable.

Function:
```function y = mysum(x,T) %#codegen y = zeros(size(x), 'like', T.y); for n = 1:length(x) y(:) = removefimath(y) + x(n); end end```
Types Table:
```function T = mytypes(dt) switch(dt) case 'fixed' T.x = fi([],1,16,0, 'RoundingMethod', 'Floor',... 'OverflowAction','Wrap'); T.y = fi([],1,16,0, 'RoundingMethod','Nearest'); end end```
Types Table:
```function T = mytypes(dt) switch(dt) case 'fixed' T.x = fi([],1,16,0, 'RoundingMethod','Floor',... 'OverflowAction','Wrap'); T.y = fi([],1,16,0, 'RoundingMethod', 'Nearest'); end end```

Was this topic helpful?

Get trial now