FUNCTION (INPUTS) Problem: I am unable to use a vector of inputs of a function as a substitute of listing the inputs each by each
조회 수: 9 (최근 30일)
Imagine to have a function myfun such that [ output ] = myfun(a,b,c,d) and output=a+b+c+d where a,b,c,d are, for the sake of simplicity, scalars then It is possibile to create a vector(1x4) v such that myfun(v) provides the same result. This works for the Matlab's built-in function SUM.
My problem is that I am not able to manage this substitution of a vector of inputs in my function:
function [ sum_err ]=mydifference(a,s,vector_p,vector_t)
err(i)= ... blablabla...
a and s are scalars, p and t are vectors
When I recall it from the command line putting mydifference(1,2,vector_p,vector_t) (i.e listing values for the scalars and vectors) everything works fine but once I create a vector_input=[1,2,vector_p,vector_t] and I evaluate my function in vector_input (i.e mydifference(vector_input) I receive this message/problem
>> mydifference(vector_input) Not enough input arguments.
I check the dimentions of my vector_input and of [a,s,vector_p,vector_t] and those match.
I don't understand how to cope with this difficulty
Adam 2017년 3월 31일
I don't know anything about fmincon as I have never used it, but I assume it works like any other function that takes a function handle input.
When you convert your function to a function handle there are two distinct types of arguments that you can mix into it - those you hard-code at the time you define the function and those you give placeholders for which you will supply later e.g.
function y = myFunc( x, a )
y = x.^a;
This is a function of two arguments, but if you require to pass it in somewhere that requires just one argument you can 'bind' the other argument at the time you declare the function handle to it, i.e.
a = 7;
f = @(x) myFunc( x, a );
f( 5 );
Here you still have your myFunc defined with its two arguments, but your function handle, f, is a function of just 1 argument. The 'a' argument has been hard-coded into the function definition so that when you call f, you just give it x and a has already been defined as 7.
You can do the same thing to pass a function to something like fmincon. Your original function can take as many arguments as it likes so long as the function handle you create for it that you will pass to fmincon sets most of them at the time you define the function handle so that is satisfies the specification of 1 input or however many it needs.
추가 답변 (1개)
Jeong-Hoon Park 2017년 7월 23일
Although there are many answer, I think I have the answer what you need to know. In MATLAB, function handle can get some parameters such as double, vector(or matrix) and so on. I think you can program this code using function handle(or inline function) which gets parameter type of vector. Like c++, vector is not need to fix the size of it. Good Luck.