setting a variable to the input
1 view (last 30 days)
Show older comments
So I have this code, when I try to run it in the command window, it keeps saying too many input arguments.
I'm trying to set r=[] open incase I want to enter mutiple variabls.
ex:
command window
r=[ 2 4 5] or r=[ 2 4 6 7 8]
roots
it keeps coming back too many inputs arguments.
function roots
r=[];
roots(r)
end
2 Comments
Tommy
on 13 May 2020
Sorry but can you explain a bit more what the goal is here?
I'm assuming you are trying to call this function with roots(r), but as you have named your function roots, MATLAB will instead call your function. And your function does not take any input arguments, so with roots(r) you are attempting to pass an input argument to a function that cannot accept an input argument.
Answers (1)
Robert U
on 13 May 2020
Hi Jian Chen,
The functionality that you describe cannot be done. Using object oriented programming the functionality could be close. With functions the call routine is different.
The function you write shadows the built-in command roots() anyway since it uses the same name. It does not make much sense to wrap an own function around a built-in function that is using the input unaltered. But for the sake of completeness there is an example for that below as well.
function p = myRoots(r)
validateattributes(r,{'numeric'},{'vector'});
p = roots(r);
end
Call it by writing to command line for r = [3 -2 -4]:
myRoots([3 -2 -4])
Class "myClass.m"
classdef myClass
properties
r; % factor representation of polynomial
end
methods
function obj = myClass(r)
% MYCLASS Construct an instance of this class
if nargin == 1
obj.r = r;
elseif nargin > 1
error('Too many inputs.')
else
% do nothing
end
end
function obj = set.r(obj,input)
% set method for property "r", check validity of input
validateattributes(input,{'numeric'},{'vector'});
obj.r = input;
end
function p = roots(obj)
% method "roots" returns polynomial roots of property "r" using built-in function "roots"
p = roots(obj.r);
end
end
end
Working with the class to achieve same result as above:
myObject = myClass([3 -2 -4]);
myObject.roots
Kind regards,
Robert
See Also
Categories
Find more on Logical 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!