MATLAB: End indexing function as method input

class definitionend indexingMATLABoopsubsref function

I have a class definition that is used to map a binary data file. When the file is initially selected, the file is mapped, that is the file scanned and the bit location where the raw data begins. I then have a method called obj.data that calls the data from the binary file using the indeces that the user inputs. obj.data is disguised as a property but it's actually a method. So the user inputs the data they want into the method like they would index a matrix.
Ex: if data is 10 x 5
obj.data(1,2) tells the method to grab the 11th value in the file (because the data is stored 50 x 1 array).
I did this with a method:
function dataOut = data(obj, varargin)
if nargin < 2 % obj.data returns the whole matrix
i = 1:nRows;
j = 1:nCols;
else
i = varargin{1};
j = varargin{2};
end
....
end
Anyway, my issue is how to deal with if the user puts in "end" to index the data. Ex: obj.data(end,1). When "end" is used as an input to this method, varagin is empty. I added a subsref method to catch ":" because ":" were actually causing an error but subsref fixed it, but subsref doesn't seem to identify "end". I tried adding an end method but it doesn't seem to get called when "end" is the input to a method. I did notice that obj.data('end',1) works but it's not intuitive to the user to do put end in quotes when indexing what they think is a property. I'd like to have it so the user doesn't have to know do anything special.
Don't know if it matters but I'm currently using Matlab 2018b.
Any ideas? Any advice would be appreciated.

Best Answer

If you create a dummy property (which is only used so Matlab treats your method as a property), you can use the overloaded subsref and end functions to call the actual code.
end is not a keyword in this context: it is a function. See this documentation page. You should be able to overload the end function with this signature:
function ind = end(A,k,n)
The arguments are described as follows:
  • A is the object
  • k is the index in the expression using the end syntax
  • n is the total number of indices in the expression
  • ind is the index value to use in the expression
You wrote an example yourself already:
classdef
properties
data = [];
end
methods
function dataOut = subsref(obj,s)
dataOut = obj.getData(s(2).subs{1},s(2).subs{2});
end
function ind = end(obj,k,n)
switch k
case 1
ind = nRows;
case 2
ind = nCols;
end
end
function dataOut = getData(obj,varagin)
if nargin < 2 % obj.data returns the whole matrix
i = 1:nRows;
j = 1:nCols;
else
i = varargin{1};
j = varargin{2};
end
obj.data = filemappingfunction(i,j);
end
end
end