Borrar filtros
Borrar filtros

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

2 visualizaciones (últimos 30 días)
Temi O
Temi O el 12 de Feb. de 2019
Respondida: Guillaume el 12 de Feb. de 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

Respuesta aceptada

Guillaume
Guillaume el 12 de Feb. de 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).

Más respuestas (0)

Categorías

Más información sobre Programming en Help Center y File Exchange.

Productos


Versión

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by