summaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
authorColton Kohnke <colton.kohnke@gmail.com>2015-10-08 21:20:37 +0200
committerColton Kohnke <colton.kohnke@gmail.com>2015-10-08 21:20:37 +0200
commit79cee63879088757cdd5c05c8d51d83a725b794d (patch)
treea7865b8098bd17d61b46d16f0b2e512192eb14d9
parentabd7444f9e5343f597b561a69297122142881fc8 (diff)
[matlab/en] Added simple class example to Matlab
-rw-r--r--matlab.html.markdown54
1 files changed, 54 insertions, 0 deletions
diff --git a/matlab.html.markdown b/matlab.html.markdown
index 02fe5962..0cbc6f57 100644
--- a/matlab.html.markdown
+++ b/matlab.html.markdown
@@ -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