Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting a property of an object in Matlab

Tags:

oop

matlab

So I am having trouble setting specific properties of an object. I am relatively new to Matlab and especially to object oriented programming. Below is my code:

classdef Card < handle
properties
    suit;
    color;
    number;
end

methods
    %Card Constructor
    function obj= Card(newSuit,newColor,newNumber)
      if nargin==3
        obj.suit=newSuit;
        obj.color=newColor;
        obj.number=newNumber;
      end
    end

    function obj=set_suit(newSuit)
        obj.suit=(newSuit);
    end

It all runs fine, until I attempt the set_suit function. This is what I've typed in the command window.

a=Card

a = 

Card handle

Properties:
  suit: []
 color: []
number: []

Methods, Events, Superclasses

a.set_suit('Spades')
Error using Card/set_suit
Too many input arguments.

This always returns the error of too many input arguments. Any help with this and object oriented programming in general would be greatly appreciated.

like image 790
Aaron Avazian Avatar asked Oct 05 '22 19:10

Aaron Avazian


1 Answers

For class methods (non static) the first argument is the object itself. So, your method should look like:

function obj=set_suit( obj, newSuit)
    obj.suit=(newSuit);
end

Note the additional obj argument at the beginning of the argument list.

Now you may call this method either by

a.set_suit( 'Spades' );

or

set_suit( a, 'Spades' );
like image 97
Shai Avatar answered Oct 09 '22 17:10

Shai