I have a huge value class. Because I'm afraid of further problems, I don't want it to be a HandleClass by now.
Anyway, I want to change a class property from a class method. Is this possible under any circumstances? I made an example and modifyValue is the critical function:
testClass.m:
classdef testClass
properties
a
end
methods
function obj = testClass()
obj.a = [1 2 3; 4 5 6];
end
function obj = modifyValue(obj)
obj(:,2) = [];
% won't work as well
obj.a(:,2) = [];
end
end
end
subsasgn.m:
function obj = subsasgn(obj, S, value)
if isempty(value)
obj.a(:,S.subs{2}) = [];
else
obj = builtin('subsasgn',obj, S, value);
end
end
Why isn't it possible to call obj(:,2) = []; from within the object? This confuses me. I'm still using Matlab R2007b, but solutions for newer versions are also very welcome.

 採用された回答

per isakson
per isakson 2014 年 3 月 26 日
編集済み: per isakson 2014 年 3 月 26 日

2 投票

The overloaded subsasgn doesn't work in the objects own methods. R2014a doc says:
Within a class's own methods, MATLAB calls the built-in subsasgn, not
the class defined subsasgn. This behavior enables to use the default
subsasgn behavior when defining specialized indexing for your class.
See subsref and subsasgn Within Class Methods — Built-In Called for
more information.
In R2007b the new "OO-syntax" was still beta.
.
Try this (it works according to my expectations)
>> clear all, clear classes
>> ca = testClass_a;
>> ca.a
ans =
1 2 3
4 5 6
>> ca = ca.modifyValue;
>> ca.a
ans =
1 3
4 6
>>
where
classdef testClass_a
properties
a
end
methods
function obj = testClass_a()
obj.a = [1 2 3; 4 5 6];
end
function obj = modifyValue(obj)
obj.a(:,2) = [];
end
end
end

3 件のコメント

Vincent
Vincent 2014 年 3 月 27 日
So I'll have to stick to the call
ca = ca.modifyValue
and there's no possibility to avoid the equal sign?
per isakson
per isakson 2014 年 3 月 27 日
Yes, there is no way to avoid the equal sign with value objects. See
Vincent
Vincent 2014 年 3 月 31 日
alright, thank you.

サインインしてコメントする。

その他の回答 (0 件)

製品

質問済み:

2014 年 3 月 26 日

コメント済み:

2014 年 3 月 31 日

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by