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
Show older comments
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=[];
for i=1:45
err(i)= ... blablabla...
i=i+1;
end;
sum_err=sum(err);
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
2 Comments
I'm not sure why you are trying to combine all your arguments into a single vector. Your function takes explicitly 4 arguments and uses them by name so it will expect you to pass in all 4 unless one is not actually used, in which case it won't care if it was passed in or not (provided it is at the end of the list).
If you want to be able to program something that accepts either
[1, 2, 3] or 1, 2, 3
as arguments like some builtin functions then you have to do a fair amount of ugly work on handling the input arguments and almost certainly you would have to just use
doc varargin
to deal with the variable number of arguments. In a general situation it really isn't worth the effort.
enzo fiasco
on 31 Mar 2017
Accepted Answer
More Answers (1)
Jeong-Hoon Park
on 23 Jul 2017
0 votes
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.
Categories
Find more on Startup and Shutdown in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!