Home > Mobile >  How to find and check obects with all properties being empty in Matlab?
How to find and check obects with all properties being empty in Matlab?

Time:08-10

For example, I create a student with all properties being empty

classdef student < handle

    properties
        name
        test
    end

    methods


        function obj = student(name)
            if nargin==1
            obj.name = name;
            obj.test = test();
            end
        end
    end
end
>> A=student

A = 

  student with properties:

    name: []
    test: []

>> isempty(A)

ans =

  logical

   0

But the output of isempty(A) is false. So what function can check if all properties of an object are empty? And How to find that kind of objects in a database?

CodePudding user response:

Not many more choices than to loop through the properties of your object to check if they are all empty or not:

function isE = check_emptyness(A)

    props = properties(A);
    isE = true;

    for iprop = 1:length(props)
      
        if ~isempty(A.(props{iprop}))
    
            isE = false;
            break
    
        end    
    end
end

student_arr=[student('A') student()];

check_emptyness(student_arr(1))

ans =

logical

0

check_emptyness(student_arr(2))

ans =

logical

1

CodePudding user response:

You can overload the isempty method for your class:

classdef student < handle

    properties
        name
        test
    end

    methods
        function obj = student(name)
            if nargin==1
               obj.name = name;
               obj.test = test();
            end
        end

        function res = isempty(obj)
            res = isempty(obj.name) && isempty(obj.test);
        end
    end
end

Now:

>> A = student;
>> isempty(A)

ans =

  logical

   1

To find empty objects in a database, iterate over the elements in the database and check if they're empty.

  • Related