create a class for a state machine with states "on" and "off" and transition functions "switchon" and "switchoff" in matlab

main.m
classdef StateMachine
    properties
        currentState
    end
    
    methods
        function obj = StateMachine(initialState)
            obj.currentState = initialState;
        end
        
        function switchon(obj)
            if strcmp(obj.currentState, 'off')
                obj.currentState = 'on';
            else
                error('The state machine is already on!');
            end
        end
        
        function switchoff(obj)
            if strcmp(obj.currentState, 'on')
                obj.currentState = 'off';
            else
                error('The state machine is already off!');
            end
        end
    end
end
668 chars
28 lines

This class defines a state machine with two states 'on' and 'off' and two transition functions 'switchon' and 'switchoff'. The state machine is initialized with the initial state, which could be either 'on' or 'off'. The switchon and switchoff methods transition the state machine between states while checking if the desired state is not the current state. If the desired state is the same as the current state, an error is thrown.

gistlibby LogSnag