How to handle 'end' in overloaded subsref?
Show older comments
I have a class with two properties, ()-indexing should only affect the property foo. This works, but when I use end, this is handled as if it were 1:
>> s = Subscriptable([1, 2; 3, 4], 'a')
s =
2×2 Subscriptable array with properties:
foo: [2×2 double]
bar: 'a'
>> s(end, :)
type: '()'
subs: {[1] ':'}
ans =
1×2 Subscriptable array with properties:
foo: [1 2]
bar: 'a'
I expected s.foo to be [3, 4]. (and within Subscriptable.subsref I expected S.subs to be either {'end', ':'} or {2, ':'}).
How can I fix this? I am using Matlab 9.9.0.1467703 (R2020b)
The code of the class Subscriptable is given below.
Thanks in advance!
classdef Subscriptable
properties
foo
bar
end
methods
function obj = Subscriptable(foo, bar)
obj.foo = foo;
obj.bar = bar;
end
function out = length(obj)
out = length(obj.foo);
end
function out = numel(obj)
out = numel(obj.foo);
end
function out = size(obj, varargin)
out = size(obj.foo, varargin{:});
end
function obj = subsasgn(obj, S, values)
switch [S.type]
case '()'
assert(isnumeric(S.subs{1}))
obj.foo(S.subs{1}) = values;
otherwise
obj = builtin('subsasgn', obj, S, values);
end
end
function out = subsref(obj, S)
% does not work with 'end' :(
disp(S)
switch [S.type]
case '()'
out = obj;
out.foo = obj.foo(S(1).subs{:});
otherwise
out = builtin('subsref', obj, S);
end
end
end
end
Accepted Answer
More Answers (0)
Categories
Find more on Create System Objects in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!