Error while calling a function a class
6 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Jithesh A
le 11 Avr 2018
Modifié(e) : James Tursa
le 11 Avr 2018
Hi all, Please help. I have a file with the name Bandit.m. It has a class defined Bandit. Code is as follows:
********************
classdef Bandit
properties
m
mean_val
N
end
methods
function self = Bandit(m)
self.m = m;
self.mean_val = 0;
self.N = 0;
end
function reward = pull_arm()
reward = randn() + self.m;
end
end
end
********************
Now, I have another file called test.m in the same directory. I run the following line and get the error. Code is as follows:
a = Bandit(5);
a.pull_arm();
when I run the above code, I get "Too many input arguments.". Am I doing some mistakes in the above 2 lines of code? I have been working with Python, but using MATLAB for the first time.
I am new to MATLAB. Can somebody help?
0 commentaires
Réponse acceptée
Steven Lord
le 11 Avr 2018
" a.pull_arm();" is equivalent to "pull_arm(a);". [There could be a difference if your method accepted two inputs, but for this particular case there isn't.] From the documentation:
"MATLAB differs from languages like C++ and Java® in that there is no special hidden class object passed to all methods. You must pass an object of the class explicitly to the method. The left most argument does not need to be the class object, and the argument list can have multiple objects. MATLAB dispatches to the method defined by the class of the dominant argument."
You can name that explicit input argument self if you want.
function reward = pull_arm(self)
reward = randn() + self.m;
end
I suspect you may want pull_arm to update a property of the object self. If that's the case you need to do one of two things. The first approach would be to call the function with the object instance as both input and output:
function self = pull_arm(self)
self.m = randn() + self.m; % Assuming m is the cumulative reward
end
and invoke this method as:
myBandit = pull_arm(myBandit);
0 commentaires
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Environments dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!