object oriented program that can add element to cell, find the first element in a cell, find the last element in a cell in matlab

Here's a simple object-oriented Matlab class MyCell that allows you to add elements to a cell array, find the first element in the cell array, and find the last element in the cell array:

main.m
classdef MyCell
   properties
      cell_array
   end
   methods
      function obj = MyCell()
         obj.cell_array = {};  % Initialize an empty cell
      end
      function addElement(obj, element)
         obj.cell_array{end + 1} = element;  % Add an element to the end of the cell
      end
      function firstElement = findFirstElement(obj)
         if ~isempty(obj.cell_array)  % Check if the cell is not empty
            firstElement = obj.cell_array{1};  % Return the first element
         else
            firstElement = [];  % Return an empty array if the cell is empty
         end
      end
      function lastElement = findLastElement(obj)
         if ~isempty(obj.cell_array)  % Check if the cell is not empty
            lastElement = obj.cell_array{end};  % Return the last element
         else
            lastElement = [];  % Return an empty array if the cell is empty
         end   
      end
   end
end
931 chars
28 lines

To use this class, you can create an object of MyCell and call its methods like this:

main.m
>> my_cell = MyCell;
>> my_cell.addElement(1);
>> my_cell.addElement(2);
>> my_cell.addElement(3);
>> my_cell.cell_array
ans = 
    [1]    [2]    [3]
>> my_cell.findFirstElement()
ans =
     1
>> my_cell.findLastElement()
ans =
     3
235 chars
14 lines

gistlibby LogSnag