Calling the size of an input
4 views (last 30 days)
Show older comments
I call different models in a function. I want to call the size of the inputs (number of parameters the model takes) from the function I'm calling them. E.g.,
function y = model1(t,x,Pm,Other_Inputs)
Some stuff = Pm(1);
Some other stuff = Pm(2);
...
More stuff = Pm(n);
%some stuff it does using the inputs.
end
Now I want to call it with something like
function x = caller(Model)
%For example
P = size(Pm,1)
z = randi(P,1));
[~,yx2] = ode15s(@(t,x) model1...
(t,x,z,Other_Inputs)t,InitalValue);
end
Is this possible? I know some basics about varargin and nargin, but I'm not sure if they are what I should use here. Thanks for any help.
2 Comments
Jan
on 18 Jan 2017
I do not understand the question. What is "P" in the caller? Where is the problem? Which step does not work?
Accepted Answer
Star Strider
on 18 Jan 2017
‘I also have to specify how many parameters the model takes as an input.’
If ‘Pm’ is a vector and all the parameters are in the same order, the models themselves can decide.
For example:
function out1 = model1(t,x,Pm,Other_Inputs)
N = 3;
P1 = Pm(1:N);
. . .
end
function out2 = model2(t,x,Pm,Other_Inputs)
N = 5;
P2 = Pm(1:N);
. . .
end
This assumes I understand what you want to do.
4 Comments
More Answers (1)
Steven Lord
on 18 Jan 2017
So you want to turn some unknown number of parameters into individual inputs of another function? In this case I would use a cell array and turn it into a comma-separated list when you call the other function. Put the following code in a file named helper.m:
function helper(vectorOfParameters)
cellOfParameters = num2cell(vectorOfParameters);
showParameters(cellOfParameters{:});
function showParameters(varargin)
for whichParameter = 1:nargin
fprintf('Parameter %d is %g.\n', whichParameter, varargin{whichParameter});
end
Try calling the main function like this:
helper(1:5)
helper([99 4334 237 1 55 999 -17 6])
Inside helper, the num2cell function accepts the vector of parameters and creates a cell array of the same length with each element of the vector stored in the corresponding cell of the cell array. When I call showParameters, I use this syntax: cellOfParameters{:} which is just like:
showParameters(cellOfParameters{1}, cellOfParameters{2}, cellOfParameters{3}, ...)
except I don't have to write out all 1, 2, 3, 20, etc. parameters in the function call. Then inside showParameters I iterate over the number of inputs MATLAB passed into the function (which the nargin function returns) and use the loop variable to index into the cell array varargin.
See Also
Categories
Find more on Data Representation in Generated Code 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!