MATLAB Answers

setting a variable to the input

3 views (last 30 days)
Jian Chen
Jian Chen on 13 May 2020
Commented: Jian Chen on 16 May 2020
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
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.
Jian Chen
Jian Chen on 16 May 2020
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.

Sign in to comment.

Answers (1)

Robert U
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])
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 Comment

Jian Chen
Jian Chen on 16 May 2020
Yeah, I just reaized that i'm adding extra step to something thats aleady giving.
Thanks for the help.

Sign in to comment.