Adapt C# Set/Get class methods into MATLAB class -
take following custom c# class example, represents point:
public class point { // attributes: double x; double y; // constructor: public point(double x, double y) { this.x = x; this.y = y; } // methods: public void setx(double x) { this.x = x; } public void sety(double y) { this.y = y; } public double getx() { return this.x; } public double gety() { return this.y; } }
i adapt same class matlab. goal implement set , methods , constructor, similar possible c# way.
i aware matlab not allow self-reference, read on this question. however, know should problably want start class following header:
classdef point < handle
i read here , here. statement declare custom point
class matlab handle
class, having inherit handle superclass. understand allow me implement set/get functionality trying emulate, constructor.
this have far:
classdef point < handle % attributes properties (access = private) x = []; y = []; end % methods methods % constructor: first method, must have same name class. function point(x,y) end % set , methods: function setx(x) end ... end end
from point on, don't know how continue.
first describe in comments question, lets first simplify c# using properties:
public class point { public point(double x, double y) { this.x = x; this.y = y; } public double x { get; set; } public double y { get; set; } }
now create similar class in matlab indeed have create classdef
file , if want mimic pass reference you'll have derive handle
class else object passed value. using properties maltab class like:
classdef point < handle methods function [this] = point(x, y) this.x = x; this.y = y; end end properties x; y; end end
now suppose need implement setters/getters validation purpose example. c# class like:
public class point { public point(double x, double y) { this.x = x; this.y = y; } private double x; // back-store public double x // setters , getters { { return x; } set { if (value < 0.0) { throw new invalidargumentexception("x must positive"); } x = value; } } ... same 'y' ... }
you can implement similar getter/setter in matlab using dependent properties concept. syntax quite similar c# 1 while little more over-verbose:
classdef point < handle methods function [this] = point(x, y) this.x = x; this.y = y; end end % back-store in c# properties(setaccess=private, getaccess=private) x; y; end % setters , getters using dependent properties properties(dependent) x; y; end % definition setters , getters methods function [value] = get.x(this) value = this.x; end function [] = set.x(this, value) if (value < 0.0), error('x must positive'); end this.x = value; end ... same 'y' ... end end
for further check similarities and differences in object oriented programming concepts , implementations between matlab , c# recommand read documentation on mathworks website.
Comments
Post a Comment