Using containers.Map as a Class's property

조회 수: 17 (최근 30일)
Saurav
Saurav 2017년 3월 24일
편집: Guillaume 2017년 3월 27일
I am having a problem in Matlab while using container.Map as a property of a class. I have a class Sensor with one property which is an object of containers.Map. The problem is, I cannot modify this property for one Sensor object without modifying map in other Sensor object. This property looks to be shared among objects of class Sensor. See below for explanation.
classdef Sensor
properties
id
map=containers.Map;
end
end
s1=Sensor;
s2=Sensor;
s1.map('key1')='value1';
s2.map
At this point s2.map also has same content as s1.map.
Has anyone faced this before or any particular solution. I just changed from table to containers.Map because of the flexibility and speed.
Thanks Saurav

채택된 답변

Steven Lord
Steven Lord 2017년 3월 24일
From the documentation for how to initialize property values:
"There are two basic approaches to initializing property values:
  • In the property definition — MATLAB evaluates the expression only once and assigns the same value to the property of every instance.
  • In a class constructor — MATLAB evaluates the assignment expression for each instance, which ensures that each instance has a unique value."
You're initializing the property to a containers.Map in the property definition, and additionally a containers.Map has handle semantics. Initialize it instead in the constructor.
  댓글 수: 1
Saurav
Saurav 2017년 3월 27일
Thanks very much, I didn't have a clue about it.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Graphics Performance에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by