How to remove the data from a handle class from memory

10 ビュー (過去 30 日間)
Olaf Bousche
Olaf Bousche 2015 年 8 月 5 日
コメント済み: Olaf Bousche 2015 年 8 月 13 日
I feel like an idiot but I don't seem to be able to solve the following problem:
When I define a handle class, how do I destroy it?
Example:
classdef test_class < handle
properties
% Lots of data
data = rand(1e4,1e4);
end
methods
function delete(obj)
% What do I put here to destroy the object itself: erase the object itself from memory
% Only "clear all" seems to work
end
end
end
Testing this with
x = test_class;
clear x
memory
clear all
memory
shows that the class data is effectively destroyed by clear all.
Does anyone know what code to use in the delete function ??
Thanks for you replies
Olaf

採用された回答

Ghada Saleh
Ghada Saleh 2015 年 8 月 7 日
Hello Olaf,
I understand you want to clear the class definition in the 'delete' method. You can use the following command:
clear classes;
Note that this command issues a warning and does not clear a class of objects if any of those objects still exists after the workspace is cleared. For example, objects can still exist in persistent variables of functions or figure windows. Also, lear classes does not clear a class if its file is locked using the mlock command. No warning is issued in this case.
Also, if you are using MATLAB R2012b or earlier versions, note that there is a bug when using clear classes. This bug is fixed in R2013a.
I hope this helps,
Ghada
  1 件のコメント
Olaf Bousche
Olaf Bousche 2015 年 8 月 13 日
Dear Ghada:
Thanks for your response. The clear classes provide only a partial solution for what I wanted. The problems I had with classes with a lot of data eating all my memory where caused by my misunderstanding on how to uses such classes. When you want to use such classes I should have created a class constructor. The following definition solves the problem:
classdef test_class < handle
properties
% Just the property
data;
end
methods
% Creator goes here
function obj = test_class()
obj.data = rand(1e4); % All the data
end
end
end
A simple clear or delete command now clears the data.
I got this answer from Matlab support.
Olaf

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeGet Started with MATLAB についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by