MATLAB Answers

Translated by

このページのコンテンツは英語から自動翻訳されています。自動翻訳をオフにする場合は「<a class="turn_off_mt" href="#">ここ</a>」をクリックしてください。

0

Create a method that overloads a property?

Dominik Mattioli さんによって質問されました 2017 年 10 月 25 日
最新アクティビティ Cedric Wannaz
さんによって 編集されました 2017 年 10 月 25 日
I have an established object I would like to overload one of its properties by creating a method of the same name.
My idea for solving this predicament is to create a method of the same name as the property that simply filters out the non-positive inputs and returns the positive inputs that the original property would otherwise return. Currently, the method of myProp is underlined red because its use is "inconsistent with its previous use".
classdef myObj
properties
myProp % This is an Mx3 matrix.
end
methods
function obj = myObj() % Instantiate.
obj.myProp = randi(9,5,3);
end
function myProp_Output = myProp(rows,columns)
%MYPROP Returns data of myProp while accomodating for
%non-positive row inputs.
idx0 = rows == 0;
myProp_Output = zeros(length(rows),columns);
myProp_Output(~idx0,columns) = myObj.myProp(rows(~idx0),columns);
end
end
end
I would like to do this because I've created some code that creates arrays for indexing that might have some non-positive indices (zero) and sometimes I use these arrays to index into a property of my object. I've read a little documentation on overloading in MATLAB but I haven't yet found anything that would help me overload a property of an object with a method.
For example:
obj = myObj(); % Instantiate w random integers
indices = [0 3 5];
obj.myProp(indices,:) % Doing this will result an error because of the non-positive index.
I would like this to be the output:
[0 0 0; obj.myProp(3,:); obj.myProp(5,:)]

  0 件のコメント

サインイン to comment.

1 件の回答

回答者: Cedric Wannaz
2017 年 10 月 25 日
編集済み: Cedric Wannaz
2017 年 10 月 25 日
 採用された回答

We usually do this using setters and getters. You will find plenty of doc if you google these terms, e.g. this for SET and this for GET.
EDIT: if you are just starting OOP, congratz., you just spontaneously tried to invent an important mechanism! Looking at the following page of the doc will give you an idea of what exists on the matter:

  0 件のコメント

サインイン to comment.



Translated by