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

2 次查看(过去 30 天)
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

采纳的回答

Guillaume
Guillaume 2019-2-12
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).

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Programming 的更多信息

产品


版本

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by