setting a variable to the input
조회 수: 3 (최근 30일)
이전 댓글 표시
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
Tommy
2020년 5월 13일
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.
답변 (1개)
Robert U
2020년 5월 13일
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
참고 항목
카테고리
Help Center 및 File Exchange에서 Read, Write, and Modify Image에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!