setting a variable to the input

1 次查看(过去 30 天)
Jian Chen
Jian Chen 2020-5-13
评论: Jian Chen 2020-5-16
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
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.
Jian Chen
Jian Chen 2020-5-16
My original goal is to be able to have the user enter any amounts of the variables r and have it solve for roots, but then I just realized that I was adding extra steps to something thats already solved.
Thanks for explaining it to me.

请先登录,再进行评论。

回答(1 个)

Robert U
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])
Object oriented programming - Mathworks Classes Basics
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
  1 个评论
Jian Chen
Jian Chen 2020-5-16
Yeah, I just reaized that i'm adding extra step to something thats aleady giving.
Thanks for the help.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by