How to return function arguments as a struct?

20 views (last 30 days)
Hello people,
I am trying to create a function to help me solve some tedious math operations. I use a switch-case structure to compute different things depending on the input arguments, compute all the math and then return all the important information on a struct. Here is my code (I've deleted some case just do the example clearer):
function [varargout] = designSpec(varargin)
switch varargin{1}
% Case 1: ts and Mp are given
case 1
% Assign the variables
ts = varargin{2}; % variables(1);
Mp = varargin{3}/100; %variables(2)/100;
% Validation of input arguments
if nargin < 3
error('Invalid number of inputs. Tolerance criteria for ts must be specified.');
elseif varargin{4} == 2 % tolerance == 2
ts_num = 4;
elseif varargin{4} == 5
ts_num = 3;
% Get the dominant poles
damping = sqrt((log(Mp)^2)/((pi^2+(log(Mp)^2))));
wn = ts_num/(damping*ts);
sigma = -damping*wn; % real component
wd = wn*sqrt(1-damping^2); % complex component
poles = [sigma+wd*1i sigma-wd*1i];
equation = poly(poles);
% Case 2: tp and Mp are given
case 2
% Assign the variables
tp = varargin{2};
Mp = varargin{3}/100;
% Get the dominant poles
wd = pi/tp; % complex component
tg_theta = -pi/log(Mp); % aux variable
damping = sqrt(1/(1+tg_theta^2));
wn = wd/sqrt(1-damping^2);
sigma = -damping*wn; % real component
poles = [sigma+wd*1i sigma-wd*1i];
equation = poly(poles);
varargout{1} = equation;
varargout{2} = poles;
varargout{3} = wn;
varargout{4} = damping;
The problem is that when I call the function it returns just the first argument of the function instead of returning a struct with all the variables in it. There is something that I'm missing on my code? Am I calling the function properly?
  1 Comment
Stephen23 on 6 Aug 2022
"There is something that I'm missing on my code?"
There is absolutely no "struct" involved anywhere in your code. You also don't use VARARGOUT in any way that makes use of its purpose (allowing a variable number of output arguments).
Your code is equivalent to simply defining the function signature as:
function [equation,poles,wn,damping] = designSpec(varargin)

Sign in to comment.

Accepted Answer

Paul on 6 Aug 2022
Change the signature of the function to
function out = designSpec(varargin)
At the bottom of the function assign to the struct fields
out.equation = equation;
out.poles = poles;
out.wn = wn;
out.damping = damping;

Sign in to comment.

More Answers (0)


Find more on Argument Definitions in Help Center and File Exchange




Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!