[matlab/en] Added simple class example to Matlab

This commit is contained in:
Colton Kohnke 2015-10-08 21:20:37 +02:00
parent abd7444f9e
commit 79cee63879

View File

@ -3,6 +3,7 @@ language: Matlab
contributors:
- ["mendozao", "http://github.com/mendozao"]
- ["jamesscottbrown", "http://jamesscottbrown.com"]
- ["Colton Kohnke", "http://github.com/voltnor"]
---
@ -464,6 +465,59 @@ mean % mean value
std % standard deviation
perms(x) % list all permutations of elements of x
% Classes
% Matlab can support object-oriented programming.
% Classes must be put in a file of the class name with a .m extension.
% To begin, we create a simple class to store GPS waypoints.
% Begin WaypointClass.m
classdef WaypointClass % The class name.
properties % The properties of the class behave like Structures
latitude
longitude
end
methods
% This method that has the same name of the class is the constructor.
function obj = WaypointClass(lat, lon)
obj.latitude = lat;
obj.longitude = lon;
end
% Other functions that use the Waypoint object
function r = multiplyLatBy(obj, n)
r = n*[obj.latitude];
end
% If we want to add two Waypoint objects together without calling
% a special function we can overload Matlab's arithmetic like so:
function r = plus(o1,o2)
r = WaypointClass([o1.latitude] +[o2.latitude], ...
[o1.longitude]+[o2.longitude]);
end
end
end
% End WaypointClass.m
% We can create an object of the class using the constructor
a = WaypointClass(45.0, 45.0)
% Class properties behave exactly like Matlab Structures.
a.latitude = 70.0
a.longitude = 25.0
% Methods can be called in the same way as functions
ans = multiplyLatBy(a,3)
% The method can also be called using dot notation. In this case, the object
% does not need to be passed to the method.
ans = a.multiplyLatBy(a,1/3)
% Matlab functions can be overloaded to handle objects.
% In the method above, we have overloaded how Matlab handles
% the addition of two Waypoint objects.
b = WaypointClass(15.0, 32.0)
c = a + b
```
## More on Matlab