4

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?

2 Answers2

4

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?

Navan
  • 4,407
  • 1
  • 24
  • 26
  • Good answer. I'll try to figure out if I could solve my problem this way when I'm at my desk tomorrow. Another conceivable approach would be to iterate over an array of `measurementHandler` objects - which doesn't seem to work with **MATLAB Function** blocks either, does it? – Christian Reimer Sep 26 '13 at 19:22
  • 1
    Array of objects are not supported in MATLAB Function block. – Navan Sep 26 '13 at 20:37
  • Got it to work. 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. This way, the for loop gets unrolled at compile time and the return type of the function is well defined for each separate call. Thanks for putting me on the right track! – Christian Reimer Sep 27 '13 at 06:50
2

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.