MATLAB Answers

Classdef get methods: allowing get indexing into an array of length either (1x1) or (Nx1).

조회 수: 3(최근 30일)
D. Plotnick
D. Plotnick 27 Mar 2019
Commented: D. Plotnick 28 Mar 2019
Hello all, I am trying to sort out an issue best shown in this MWE, where I have a property that may be a column vector, but is initialized with a single value.
classdef myClass
properties
A (:,1) double = 0;
end
methods
end
end
Now, lets say I want to index into myClass.A using B = myClass.A(indx). However, I want it so that if myClass.A is still a (1x1) I want to return the initial value, not an "Index exceeds array bounds" error.
I can picture doing this with a get method of the following form
function out = get.A(indx)
if numel(obj.A) == 1
out = obj.A(1);
else
out = obj.A(indx);
end
end
However, this will clearly not work since (A) get methods are limitited to one input, and I need to pass "indx", (B) I don't pass an instance of the object to get.A, so it has no access, and (C) this would wind up being infinitely recursive if I was able to do it.
SO:
Is there a way to allow use of a single default value as the output of a property regardless of the requested index, if that property has not yet been overwritten with an Nx1 vector.
Cheers,
DP

  댓글 수: 0

로그인 to comment.

채택된 답변

Catalytic
Catalytic 27 Mar 2019
Catalytic 님이 편집함. 27 Mar 2019
You would need to overload subsref, e.g.,
methods
function out=subsref(obj,S)
if S(1).type=="." && S(1).subs{1}=="A" && numel(S)>1
out=obj.A(min(S(2).subs{1},1));
else
error 'Undefined Indexing'
end
end
end

  댓글 수: 1

D. Plotnick
D. Plotnick 28 Mar 2019
Darn. I was hoping someone had another idea in the last day, because I really don't want to overload subsref or any other low level Matlab functions. Thanks for the input, I hadn't even thought of that, I may just need to bite the bullet and put the check:
if indx > length(obj.A)
indx = 1;
end
val = obj.A(indx);
into all of the higher level functions, rather than something in the class definition itself.

로그인 to comment.

More Answers (1)

Sean de Wolski
Sean de Wolski 28 Mar 2019
Sean de Wolski 님이 편집함. 28 Mar 2019
You could GetAccess Protect the A property and then use a method instead of straight property reference.
methods
function a = getA(obj, indx)
if numel(obj.A) == 1 || nargin == 1
out = obj.A(1);
else
out = obj.A(indx);
end
end
end

  댓글 수: 1

D. Plotnick
D. Plotnick 28 Mar 2019
Thanks. That is indeed less invasive than overloading subsref.

로그인 to comment.

이 질문에 답변하려면 로그인을(를) 수행하십시오.


Translated by