cmatlabcode-generationmexmatlab-coder

Cannot convert Matlab code to C code using Matlab Coder


I have a MATLAB code shown in below. I am trying to convert this code to C code using MATLAB Coder but I encountered an error.

enter image description here

Expected either a logical, char, int, fi, single, or double. Found an mxArray. MxArrays are returned from calls to the MATLAB interpreter and are not supported inside expressions. They may only be used on the right-hand side of assignments and as arguments to extrinsic functions.

% Applies A-weighted filtering to sound and draws it's plot
% in a figure as output.
function A_filtering
coder.extrinsic('tic')
coder.extrinsic('toc')
coder.extrinsic('display')
sampleRate = 44100;
reader = dsp.AudioFileReader('Jet_Flypast.wav');
fs = 44100;
weightFilter = weightingFilter('A-weighting',fs);
% fileWriter = dsp.AudioFileWriter('SampleRate',fs);
% visualize(weightFilter,'class 1')
scope = dsp.SpectrumAnalyzer('SampleRate',fs,...
    'PlotAsTwoSidedSpectrum',false,...
    'FrequencyScale','Log',...
    'FrequencyResolutionMethod','WindowLength',...
    'WindowLength',sampleRate,...
    'Title','A-weighted filtering',...
    'ShowLegend',true,...
    'ChannelNames',{'Original Signal','Filtered Signal'});

tic
while toc < 60
    x = reader();
    y = weightFilter(x);
    scope([x(:,1),y(:,1)])
    display(x(:,1))
end

release(scope);
release(weightFilter);
release(reader);
end

This question might be a duplicate but I searched internet and couldn't find any related posts. Is there any way to solve this error?


Solution

  • You have declared tic, toc as extrinsic which is correct since they are not supported for code generation. Since they are extrinsic, the results from these functions cannot be directly used in other expressions. Coder does not know the contents of these results at run-time. But you can provide hints on their types by assigning their results to known variables. You should replace the line

    while toc < 60
    

    with the following lines

    tElapsed = 0;
    tElapsed = toc;
    while tElapsed < 60
    

    Since we initialized tElapsed with a 0, it is a known type of double scalar. Output of toc will be converted to this type when it is assigned to tElapsed.

    Also note that your code will work fine when you generate a mex file using MATLAB Coder. But you cannot generate standalone code from this since extrinsic functions need MATLAB to run.