How to remove user-defined objects from memory?

2 ビュー (過去 30 日間)
Chaitanya Jha
Chaitanya Jha 2019 年 11 月 7 日
コメント済み: Chaitanya Jha 2019 年 11 月 8 日
Hi, let's say I have two classes A_Class() and B_Class(). The A_Class() is defined something like this:
classdef A_Class < handle
properties
B;
end
methods
function obj = A_Class()
obj.B{1} = B_Class();
obj.B{2} = B_Class();
obj.B{3} = B_Class();
end
end
end
I create an object of class A_Class(),
A = A_Class;
Then I run the following command:
length(A.B)
and the answer is 3, which is correct. However, when I delete the object A.B{3} using the command delete(A.B{3}) the object gets deleted but when I check for length of B using command length(A.B) the answer is still 3, why? When I try to access A.B{3} matlab tells me that it is an invalid or deleted object, but still gives an answer 3 for the length of A.B why? How can make the answer 2, which is the correct answer. This is frustrating, I tried clearing the handle A.B{3} but that does not help. Any help will be appriciated, thanks a lot in advance :)

採用された回答

Guillaume
Guillaume 2019 年 11 月 7 日
編集済み: Guillaume 2019 年 11 月 7 日
Note that this has nothing to do with objects. You don't seem to be understanding cell arrays.
Your B is a cell array. A cell array is simply a container. When you ask matlab length(B) you ask the length of the container. You've created a container with 3 slots, therefore its length is 3. It doesn't matter what is in the slot, an object, a lump of coal, or nothing, the length of the container is unchanged. Note that {} affects the content of a slot, not a slot itself. You use () to interact with the container itself.
B = {[1 2 3], 'a lump of coal', B_class}; %a container of length 3, containing various things.
B{3} = []; %replace the content of slot 3 with nothing. The container has still length 3
B(3) = []; %delete slot 3 from the container, regardless of what's in it. length is now 2
  2 件のコメント
Robert U
Robert U 2019 年 11 月 7 日
A = A_Class;
length(A.B)
ans = 3
A.B(3) = [];
length(A.B)
ans = 2
Chaitanya Jha
Chaitanya Jha 2019 年 11 月 8 日
Perfect! Thank you so much. Can't believe I was thinking that was because of how class-object relationship in Matlab.

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeManage Products についてさらに検索

製品


リリース

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by