Classdef get methods: allowing get indexing into an array of length either (1x1) or (Nx1).
2 ビュー (過去 30 日間)
古いコメントを表示
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 件のコメント
採用された回答
その他の回答 (1 件)
Sean de Wolski
2019 年 3 月 28 日
編集済み: Sean de Wolski
2019 年 3 月 28 日
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
参考
カテゴリ
Help Center および File Exchange で Construct and Work with Object Arrays についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!