Home > Net >  Can I save a function's arguments in Matlab to reuse in another function?
Can I save a function's arguments in Matlab to reuse in another function?

Time:04-05

I am using the topoplot function in Matlab as follows:

topoplot(DATA, channels, ...
    'maplimits',  topoYlim, 'electrodes', 'on', 'emarker', {'.','k',[6],1}, ...
    'whitebk', 'on', 'style', 'both', 'shading', 'interp', 'drawaxis', 'off', ...
    'numcontour', [0]);

The problem is that I have to use this function several times in different parts of the script. That really makes the script unnecessarily bulky and difficult to read.

Is there a way to save all the arguments in a variable (like a structure) so that I can just call something like:

topoplot(DATA, options)

P.S. I have tried something like:

options = splitvars(table(NaN(1,6)));
options.Var1_1 = 'maplimits'
options.Var1_2 = [-1 1]
options.Var1_3 = 'electrodes'
options.Var1_4 = 'on'
options.Var1_5 = 'emarker'
options.Var1_6 = {'.','k',[6],1}

but it doesn't work.

Thank you in advance

CodePudding user response:

You can store the arguments in a cell array as follows:

arguments = {
    'maplimits',  topoYlim, 'electrodes', 'on', 'emarker', {'.','k',[6],1}, ...
    'whitebk', 'on', 'style', 'both', 'shading', 'interp', 'drawaxis', 'off', ...
    'numcontour', [0]
};

And then use them in the function call as follows:

topoplot(DATA, channels, arguments{:});

arguments{:} generates a comma-separated list with all the contents of the cell array. It is the same as typing arguments{1}, arguments{2}, arguments{3}, ....

CodePudding user response:

Other than @Cris's suggestion (which works perfectly of course), another option is to make a local function in your script file that has all the options. Your script file then looks like this:

data1 = ...;
myTopoplot(data1, channels);
data2 = ...;
myTopoplot(data2, channels);

% Wrapper around TOPOPLOT to set up common arguments
function myTopoplot(data, channels)
topoYlim = ...;
topoplot(data, channels, ...
    'maplimits',  topoYlim, 'electrodes', 'on', 'emarker', {'.','k',[6],1}, ...
    'whitebk', 'on', 'style', 'both', 'shading', 'interp', 'drawaxis', 'off', ...
    'numcontour', [0]);
end

In some cases this can be easier to follow than having a cell array of common options.

  • Related