필터 지우기
필터 지우기

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 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