|
|
Gucky wrote:
>
>
> Hi!
>
> I have a problem with overloading SUBSREF
>
> I have an object A with e.g. two members like A.name and A.age, if
> I
> have vector of this objects my program make this vector to an
> object
> of the type A. But if I want to call now A(2) it is (of course) not
> possible, because A is one object. So I thought I overload subsref
> in
> a way, that this call a routine in subsref, which extract all the
> data of A, which is part of the previous second element.
> But the main problem is, that A(2) and e.g. A.name(2) are calling
> both the same ( ) operator, is there a way to find out if there is
> a
> "." before or after the ()?
> Or have someone another idea to handle that problem?
>
> Thank you for helping!
Hi.
I'm not exactly sure how you have to object setup, but in the
subsref.m, you have
function B = subsref(A,S)
right? S includes all of the indeces called. So if you call
A.name(2), S will have 2 structures, one for '.' and one for (2). So
maybe you can code it so that it works recurrsively. You would only
process the first S structure, and recurrsively call subsref for the
remaining S. Then it would call the appropriate function depending on
the class. This probably doesn't make sense, so here's a sample
subsref.m:
function w = subsref(w,index)
switch index(1).type
case '()'
i = index(1).subs{1};
if i <= length(fieldnames(w))
fn = fieldnames(w);
% call i-th field
w = w.(fn{i});
end
case '.'
if any(strcmp(index(1).subs,fieldnames(w)))
w = w.(index(1).subs);
else
error(sprintf('Invalid field name: %s\n',index(1).subs))
end
case '{}'
error('Cell array indexing not supported by this object')
end
% if more in index, recurrsively call subsref for the remaining
if length(index) > 1
w = subsref(w,index(2:end));
end
jiro
|
|