How to return function arguments as a struct?
조회 수: 26 (최근 30일)
이전 댓글 표시
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;
end
% 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);
end
varargout{1} = equation;
varargout{2} = poles;
varargout{3} = wn;
varargout{4} = damping;
end
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
Stephen23
2022년 8월 6일
"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)
채택된 답변
Paul
2022년 8월 6일
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;
댓글 수: 5
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Data Type Identification에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!