Aaron Avazian
Aaron Avazian

Reputation: 53

Setting a property of an object in 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.

Upvotes: 5

Views: 126

Answers (1)

Shai
Shai

Reputation: 114966

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' );

Upvotes: 4

Related Questions