What is the variable 'self' in MATLAB class?

268 views (last 30 days)
Gun-min Kim
Gun-min Kim on 24 Sep 2012
Answered: Neeraj Rajpurohit on 30 Jun 2020
Hi ! While I look through the code that includes class, I found that variable 'self' behaves like 'preserved' variable.
For example...
classdef Vocabulary < handle
words = {};
function add_word(self, word, audio_signals)
new_word = Word(word);
% Concatenate and train
self.words.(char(word)) = new_word;
add_word function has 3 arguments including 'self' argument. But this function is called with only 2 arguments, like 'add_word(word_labels(~~~), train_audio_signals(~~~))'.
Not only the 'add_word' fucntion, but also the other functions use similar way.
Can anyone tell me the usage of variable 'self'?
I really appreciate your help !

Answers (2)

Daniel Shub
Daniel Shub on 24 Sep 2012
There is nothing special about the variable "self". In MATLAB many people use "obj" instead. There is something special about the first argument to a function. The class of the first argument determines the class of the method to be used. In other words
function add_word(self, word, audio_signals)
function add_word(obj, word, audio_signals)
are the same, but
function add_word(word, audio_signals, self)
is very different.
I doubt you are calling
add_word(word_labels(~~~), train_audio_signals(~~~))
and bet you are calling
myVocabularyObject.add_word(word_labels(~~~), train_audio_signals(~~~))
where myVocabularyObject is an object of the Vocabulary class. This is essentially the same as calling
add_word(myVocabularyObject, word_labels(~~~), train_audio_signals(~~~))
It is not strictly identical if the subsref method has been overloaded ...

Neeraj Rajpurohit
Neeraj Rajpurohit on 30 Jun 2020
As Daniel has rightly written, obj is usually writtern instead of 'self' in definition of methods in MATLAB classes.
If the function you are calling is non-static, and it accesses the the object properties, then self is a must-have arguments.
As you can see in the below class, the function fullName will take no arguments while calling, but we are defining obj as a reference to the class object.
class Name
Name(1, :) char
Surname(1, :) char
function name = fullName(obj)
name = obj.Name + obj.Surname


Find more on Construct and Work with Object Arrays in Help Center and File Exchange


Community Treasure Hunt

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

Start Hunting!