Search code examples
matlabdata-structuresmatlab-figure

Structure variable as input in MATLAB function using VARARGIN


I wrote a main function in Matlab that calls other functions, each of which produces plots in a new figure. Though each function produces different plots (different colors, number of subplots, and so on) they all share some features (font, fontsize, Linewidth etc.).

In order to make it easier to modify the aforementioned shared parameter for all the MATLAB figures, I have defined in the preamble of the main function a structure variable as follows:

var.font = 'Arial Unicode MS';
var.fontsize = 13;
var.interpreter = 'none' ;

and so on for the other fields. When I call the function in this way (providing the structure as input):

function plot1( var , ... )
    fig = gcf
    fig.Position(3) = var.Position3
    fig.Position(4) = var.Position4
end

everything works fine and the functions apply the feature to each figure. But if I try to provide a variable number of input to the functions using varargin, in this way

function plot1( varargin )
    fig = gcf;
    temp = varargin(1);
    fig.Position(3) = temp.Position3;
    fig.Position(4) = temp.Position4;
end

The following error message is prompted "Struct contents reference from a non-struct array object."


Solution

  • You're indexing the cell array incorrectly (this is easily done).

    • Round parentheses ( ) give you a cell output when indexing a cell array - i.e. your temp is a 1x1 cell with the struct inside it.
    • You need curly braces { } to extract the contents of a cell array.

    Fix: use curly braces:

    temp = varargin{1};
    

    I sometimes think of cell arrays as a group of boxes, since each element (or "box" in this analogy) can basically contain anything. To extract a subset of boxes, use round parentheses. To extract the contents of the boxes, use braces. This analogy extends also to tables, where the notation is consistent.

    Here's some docs on indexing cell arrays, where the difference is described in more detail:

    https://uk.mathworks.com/help/matlab/matlab_prog/access-data-in-a-cell-array.html