Consider this MATLAB class definition and usage:
classdef MyClass
properties
Value = 10;
end
end
obj = MyClass();
disp(obj.Value);What will be printed?
classdef MyClass
properties
Value = 10;
end
end
obj = MyClass();
disp(obj.Value);Look at the default value assigned to the property.
The property Value is initialized to 10. Creating an object sets this property to 10, so disp(obj.Value) prints 10.
Examine this MATLAB class code:
classdef Test
properties
x
end
methods
function obj = Test(val)
obj.x = val;
end
end
end
obj = Test();What happens when running this code?
classdef Test
properties
x
end
methods
function obj = Test(val)
obj.x = val;
end
end
end
obj = Test();Check the constructor call and its input arguments.
The constructor Test(val) requires one input argument. Calling Test() without arguments causes a 'Not enough input arguments' error.
Given this MATLAB class:
classdef Counter
properties
Count = 0;
end
methods
function obj = increment(obj)
obj.Count = obj.Count + 1;
end
end
end
c = Counter();
c = c.increment();
disp(c.Count);What is printed?
classdef Counter
properties
Count = 0;
end
methods
function obj = increment(obj)
obj.Count = obj.Count + 1;
end
end
end
c = Counter();
c = c.increment();
disp(c.Count);Remember MATLAB classes are value classes by default.
The method increment returns the updated object. Assigning it back to c updates the property. So disp(c.Count) prints 1.
Look at this MATLAB class snippet:
classdef Sample
properties (Constant)
PI = 3.14;
end
end
obj = Sample();
disp(obj.PI);What happens when running this code?
classdef Sample
properties (Constant)
PI = 3.14;
end
end
obj = Sample();
disp(obj.PI);How do you access constant properties in MATLAB?
Constant properties can be accessed via object or class name. Here, disp(obj.PI) prints 3.14.
Consider these MATLAB classes:
classdef Base
methods
function greet(~)
disp('Hello from Base');
end
end
end
classdef Derived < Base
methods
function greet(obj)
disp('Hello from Derived');
greet@Base(obj);
end
end
end
obj = Derived();
obj.greet();What is printed?
classdef Base
methods
function greet(~)
disp('Hello from Base');
end
end
end
classdef Derived < Base
methods
function greet(obj)
disp('Hello from Derived');
greet@Base(obj);
end
end
end
obj = Derived();
obj.greet();Check how superclass methods are called from subclass.
The greet method in Derived first prints its message, then calls the greet method of Base. So both messages print in order.
