Setting an object property in Matlab

Thus, I had problems setting up certain properties of the object. I am relatively new to Matlab and especially for 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

Everything works fine until I try to execute the set_suit function. This is what I 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.

+5
source share
1 answer

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

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

obj .

a.set_suit( 'Spades' );

set_suit( a, 'Spades' );
+4

All Articles