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

2 ビュー (過去 30 日間)
Temi O
Temi O 2019 年 2 月 12 日
回答済み: Guillaume 2019 年 2 月 12 日
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 Center および File ExchangeLogical についてさらに検索

製品


リリース

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by