I have defined an abstract base class measurementHandler < handle which defines the interface for all inherited classes. Two subclasses of this class are a < measurementHandler and b < measurementHandler.

I now have a function which should return a handle to an instance of either of these subclasses (depending on the function arguments) to it's caller. Consider something like this:

function returnValue = foobar(index)
    if index == 0
        returnValue = a();
    else
        returnValue = b();
    end
end

This function is enclosed in a MATLAB Function block in Simulink (2013a). When I try to simulate the system, I get the following error:

Type name mismatch (a ~= b).

Can anybody suggest a workaround for this which still allows me to take advantage of OOP & inheritance when using Simulink?

有帮助吗?

解决方案

This kind of pattern is possible in MATLAB Function block only if the "if" condition can be evaluated at compile time. The types cannot be switched at run-time. Can you make the index value a constant at the call site?

其他提示

The main reason to use this pattern was to iterate over a measurementHandler Array, while these all can have custom implementations. I was able to do this by unrolling the loop with the coder.unroll directive. Example for the enclosing MTALAB Function block:

function result = handleAllTheMeasurements(someInputs)
%#codegen
    for index = coder.unroll(1:2)
         measurementHandler = foobar(index);
         measurementHandler.handleMeasurement(someInputs);
    end
result = something;
end

This way, the for loop gets unrolled at compile time and the return type of the function is well defined for each separate call.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top