From 79cee63879088757cdd5c05c8d51d83a725b794d Mon Sep 17 00:00:00 2001 From: Colton Kohnke Date: Thu, 8 Oct 2015 21:20:37 +0200 Subject: [matlab/en] Added simple class example to Matlab --- matlab.html.markdown | 54 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) (limited to 'matlab.html.markdown') 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 -- cgit v1.2.3