Documentation Center

  • Trial Software
  • Product Updates

Pass Property/Value Pairs

You can use varargin to pass property/value pairs in functions. However, for code generation, you must take precautions to avoid type mismatch errors when evaluating varargin array elements in a for-loop:

IfDo This:
You assign varargin array elements to local variables in the for-loopVerify that for all pairs, the size, type, and complexity are the same for each property and the same for each value
Properties or values have different sizes, types, or complexityDo not assign varargin array elements to local variables in a for-loop; reference the elements directly

For example, in the following function test1, the sizes of the property strings and numeric values are not the same in each pair:

%#codegen
function test1
    v = create_value('size', 18, 'rgb', [240 9 44]);
end
 
function v = create_value(varargin) 
    v = new_value();
    for i = 1 : 2 : length(varargin)
        name = varargin{i};
        value = varargin{i+1};
        switch name
            case 'size'
                v = set_size(v, value);
            case 'rgb'
                v = set_color(v, value);
            otherwise
        end
    end
end
...

Generated code determines the size, type, and complexity of a local variable based on its first assignment. In this example, the first assignments occur in the first iteration of the for-loop:

  • Defines local variable name with size equal to 4

  • Defines local variable value with a size of scalar

However, in the second iteration, the size of the property string changes to 3 and the size of the numeric value changes to a vector, resulting in a type mismatch error. To avoid such errors, reference varargin array values directly, not through local variables, as highlighted in this code:

%#codegen
function test1
    v = create_value('size', 18, 'rgb', [240 9 44]);
end
 
function v = create_value(varargin) 
    v = new_value();
    for i = 1 : 2 : length(varargin)
            switch varargin{i}
            case 'size'
                v = set_size(v, varargin{i+1});
            case 'rgb'
                v = set_color(v, varargin{i+1});
            otherwise
        end
    end
end
...
Was this topic helpful?