How do I make a function accept a vector as an input

1 vue (au cours des 30 derniers jours)
Temi O
Temi O le 12 Fév 2019
Please, how do I create a function called fun that accepts vector A as an input where A= [x1,x2,x3] ?
function c = fun(A)
%where A = [x1,x2,x3)
% I will call a function that I created earlier on, and then use the values of x1,x2,x3 in the called function.
end

Réponse acceptée

Guillaume
Guillaume le 12 Fév 2019
If you want to pass the first, second, third, or nth element of the input vector to your function, then tell matlab you want the 1st, 2nd, 3rd or nth element of that vector, the same way you normally index any vector or matrix. There is nothing special that happens in a function
function c = cost(par)
validateattributes(par, {'numeric'}, {'vector', 'numel', 3}); %optional but it's always a good idea to check that your input conforms to your precondtion
[mrt, mER] = dostuff(10000, par(1), par(2), 0.01, par(3));
%...
end
Doing
par = [x1, x2, x3];
is not going to somehow magically, assign par(1) to x1, par(2) to x2 and par(3) to x3. It works exactly the same way as everywhere else, and means concatenate the values of x1, x2 and x3 and assign to par. Instead you can do:
x1 = par(1);
x2 = par(2);
x3 = par(3);
But it's a waste of time (and numbered variables are a bad idea). Whenever you were going to write x1 just write par(1).

Plus de réponses (0)

Catégories

En savoir plus sur Programming dans Help Center et File Exchange

Produits


Version

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by