Error while calling a function a class

조회 수: 5 (최근 30일)
Jithesh A
Jithesh A 2018년 4월 11일
편집: James Tursa 2018년 4월 11일
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?

채택된 답변

Steven Lord
Steven Lord 2018년 4월 11일
" 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);
The second approach involves making your class a handle class.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Environments에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by