passing handle objects by value

6 ビュー (過去 30 日間)
mahdi Babayi semiromi
mahdi Babayi semiromi 2021 年 7 月 13 日
コメント済み: Yongjian Feng 2021 年 7 月 13 日
Hi
I have a class inheriting from the "handle" class, which means (correct me if I'm wrong) it will have reference semantics. I use an instance of the class in a simulation loop and I'd like to save a sanpshot of the object in every iteration. Is there a way to dereference the handle object and pass it by value to store it in a cell array?
Thanks for your replies in advance

採用された回答

Steven Lord
Steven Lord 2021 年 7 月 13 日
Have your class inherit from matlab.mixin.Copyable as described on this documentation page.
  1 件のコメント
mahdi Babayi semiromi
mahdi Babayi semiromi 2021 年 7 月 13 日
Thanks

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

その他の回答 (1 件)

Yongjian Feng
Yongjian Feng 2021 年 7 月 13 日
You don't need to.
classdef aclass < handle
properties
a
end
end
l={}
a = aclass();
a.a = 10;
l{end+1} = a;
a = aclass();
a.a = 20;
l{end+1} = a;
l{1}
l{2}
  2 件のコメント
mahdi Babayi semiromi
mahdi Babayi semiromi 2021 年 7 月 13 日
編集済み: mahdi Babayi semiromi 2021 年 7 月 13 日
Thank you very much for your reply
This is different from the application that I have in mind. my case is like the following:
classdef aClass < handle
properties
a
end
end
aClassInstance = aClass;
l = {};
for i = 1:2
aClassInstance.a = i;
% here I want to save the variable aClassInstance by value, so that I
% have it in its current state. If I just assign it to a cell array,
% like:
l{end+1} = aClassInstance;
% then l{end+1} will only hold a pointer to the variable aClassInstance
% and when I exit the loop, I'll only have access to the latest state
% of the variable
end
Yongjian Feng
Yongjian Feng 2021 年 7 月 13 日
Can you just move the initialization line inside the for loop?
classdef aClass < handle
properties
a
end
end
l = {};
for i = 1:2
aClassInstance = aClass;
aClassInstance.a = i;
% here I want to save the variable aClassInstance by value, so that I
% have it in its current state. If I just assign it to a cell array,
% like:
l{end+1} = aClassInstance;
% then l{end+1} will only hold a pointer to the variable aClassInstance
% and when I exit the loop, I'll only have access to the latest state
% of the variable
end

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

カテゴリ

Help Center および File ExchangeStartup and Shutdown についてさらに検索

製品


リリース

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by