jpo38
jpo38

Reputation: 21564

Matlab coder: "All inputs must be constant"

I'm using Matlab Coder to convert this code to C++:

fs = 50;
[b,a] = butter(3,0.5/(fs/2),'high');
...
% Other code using fs

Then, I get this error: "All inputs must be constant".

If I do: [b,a] = butter(3,0.5/(50/2),'high');, it works.

I found this post: Constants and Matlab Coder

So I tried:

fs = 50;
[b,a] = coder.const(@butter,3,0.5/(fs/2),'high');

But it still reports the same error. How can I fix this?

Upvotes: 1

Views: 1073

Answers (2)

Areej
Areej

Reputation: 13

MATLAB R2020a is now available. The function butter is enhanced in R2020a to support code generation with non-constant inputs. The generated code can be used to obtain the coefficient of any filter of valid order and cutoff frequencies at runtime.

For example, consider the below code which gives the filter coefficients of a high pass digital filter:

function[num,den] = hpbutter(n,w)
%#codegen

[num,den] = butter(n,w,'high');

Now we can generate code with non-constant inputs as follows:

codegen hpbutter -args {coder.typeof(0),coder.typeof(0)}

You can pass any valid filter order (n) and cutoff frequency(w) to the generated MEX.

[num,den] = hpbutter_mex(2,0.3)

num =

0.5050   -1.0100    0.5050

den =

1.0000   -0.7478    0.2722

[num,den] = hpbutter_mex(3,0.4)

num =

0.2569   -0.7707    0.7707   -0.2569

den =

1.0000   -0.5772    0.4218   -0.0563

Upvotes: 1

Burak
Burak

Reputation: 2495

Define Class Properties with Constant Values

In ConstInput.m

classdef ConstInput
   properties (Constant)
      fs = 50;
   end
end

Then rename fs as ConstInput.fs. (Unfortunately, Shift+Enter does not work. Maybe this links helps about changing variable names.)

Upvotes: 1

Related Questions