summaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
authorLevi Bostian <levi.bostian@gmail.com>2015-10-09 10:15:02 -0500
committerLevi Bostian <levi.bostian@gmail.com>2015-10-09 10:15:02 -0500
commitac91ec8a9c93bae3d881e74b88d8f111e93f4ec0 (patch)
treeb6bf49adb6054caac2340fb3b8120ce112a26015
parentdcd9093d6467166a2946008c55f5e0582a15e20c (diff)
parent79cee63879088757cdd5c05c8d51d83a725b794d (diff)
Merge pull request #1410 from voltnor/matlab_class_example
[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