Info

Diese Frage ist geschlossen. Öffnen Sie sie erneut, um sie zu bearbeiten oder zu beantworten.

General expression for inputting n number of arguments

3 Ansichten (letzte 30 Tage)
J OBrien
J OBrien am 21 Feb. 2016
Geschlossen: MATLAB Answer Bot am 20 Aug. 2021
Hi
This is just an example of what I am basically asking..
I have an objective function eg., f=@(a,b,c,d) a+2*b+3*c+d;
with those unknown variables [a,b,c,d]
I created an array of random numbers eg., A = [1 5 3 2];
and now I calculate my objective value eg., f_obj=abs(f(A(1),A(2),A(3),A(4));
and this gives me a numerical output.
Now my question is, how do I code f_obj to receive any number of arguments? Say, I have 3 unknowns, or 5 unknowns. The objective function is random so I don't want to have to keep updating my code if this changes. Is there a way to code a general expression? Ive seen that 'varargin' is used but I'm not sure if this is the correct solution.
Thank you

Antworten (1)

Walter Roberson
Walter Roberson am 22 Feb. 2016
function r = call_f(f)
n = abs(nargin(f));
A = num2cell( rand(1,n) );
r = f(A{:});

Diese Frage ist geschlossen.

Community Treasure Hunt

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

Start Hunting!

Translated by