Search code examples
matlabbuffersimulink

Circular buffer in Simulink implemented as MATLAB function


I am currently trying to design a very rough but functioning circular buffer for real-time signal processing. For the sake of clarity, I do not have a DSP Toolbox license.

Now, the idea is to buffer a portion of signal within a 1xN window and then further post-process. To achieve this I have been thinking a Simulink block as in the following figure.

enter image description here

The problem is the following: if the MATLAB function is

function y = fcn(Signal,DelayedBuffer,BufferSize)
%#codegen
% y = zeros(1,BufferSize);
persistent Buffer;
Buffer = [Signal DelayedBuffer(1:59-1)];

y = Buffer;
end

everything work out just fine. However, when writing the function as

function y = fcn(Signal,DelayedBuffer,BufferSize)
%#codegen
% y = zeros(1,BufferSize);
persistent Buffer;
Buffer = [Signal DelayedBuffer(1:BufferSize-1)];

y = Buffer;
end

I receive the following error:

Data 'y' (#32) is inferred as a variable size matrix, while its specified type is something else.

Do you have any valuable hint on how to suppress this error?


Solution

  • MATLAB Function block works by generating compiled code for the MATLAB code you enter. In order to generate code the block needs to know the size, type and complexity of all the inputs and variables you use. It infers the size of the variables and outputs based on the size of the inputs. When you create Buffer using

    Buffer = [Signal DelayedBuffer(1:59-1)];
    

    it is easy to see that the size of the Buffer is 59 elements (assuming Signal is scalar). MATLAB Function block can infer this size and also identify that y which is assigned Buffer also is of the same size. In the second case,

    Buffer = [Signal DelayedBuffer(1:BufferSize-1)];

    BufferSize is coming from input and MATLAB Function block does not know this value when compiling. So it has to assume that this value can change which leads to a variable-sized data. i.e It cannot determine the size of Buffer while compiling. 'y' which is assigned Buffer is also inferred as a variable-sized data. The error message indicates that you may have specified output size in the block's parameters as a fixed size. There is a check-box in the blog's "Ports and Data Manager" dialog that indicates the output port is variable size. You can check that box to see that works. But in your case, for a circular buffer, it is better to use persistent variable which gives you fixed-size data.

    It your BufferSize does not need to change within one simulation try using it as a parameter to the MATLAB Function block instead of an input. You can do this also through the "Ports and Data Manager" dialog.