Object array: modify properties of a single element

I'll try to be short.
I have the class "testClass" defined in this way:
classdef testClass<handle
properties
value=[];
end
methods
function modifyValue(input,number)
input.value=number;
end
end
end
Then, in the command window I write:
>>MyClass(1:10)=testClass;
>>MyClass(1).modifyValue(10);
The idea is to create an array of objects (made of, in this case, 10 elements). With the second line command I'd like to modify only the property ("value") of the first element of the array "MyClass", leaving the properties of the other elements "MyClass(2:end)" unchanged.
I get the following:
>> MyClass(1)
ans =
testClass with properties:
value: 10
>> MyClass(2)
ans =
testClass with properties:
value: 10
[...]
the property "value" is set equal to 10 for all the elements of the array "MyClass". How can make it work in the intended way? (e.g. "MyClass(1)" having a property "value" equal to 10 while "MyClass(2)" equal to [])
Thank you for your help and sorry for my bad english.

 Akzeptierte Antwort

per isakson
per isakson am 23 Nov. 2017
Bearbeitet: per isakson am 23 Nov. 2017
This is a bit tricky. You have created an array of ten object handles to the same underlying object. Thus, a change of the value of the property, value, by means of one handle can be referred to by all ten handles.
One way to create an array of ten different objects is
MyClass = testClass.empty(1,0);
for jj = 1 : 10
MyClass(jj) = testClass;
MyClass(jj).modifyValue(jj*10);
end
and inspect the property values
>> [MyClass.value]
ans =
10 20 30 40 50 60 70 80 90 100
And there are other more elegant ways, see Initialize Arrays of Handle Objects and Construct Object Arrays

Weitere Antworten (0)

Kategorien

Mehr zu Construct and Work with Object Arrays finden Sie in Hilfe-Center und File Exchange

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by