Equivalent of c++'s NULL or python' s None in MATLAB
Show older comments
I have a c++ code where certain variables (as well as certain user defined class objects) are set to NULL under some conditions. I'm translating this code to MATLAB. Should I assign those variables/class objects as [] (and use isempty to check conditions) or should I assign them NaN (and use isnan to check conditions)? What would be more correct and efficient? Or do i assign them to logical operator "false"?
Accepted Answer
More Answers (4)
James Tursa
on 20 May 2021
Edited: James Tursa
on 20 May 2021
1 vote
This will probably depend on how these are used downstream in your code and whether you have arrays of them to deal with. If they are scalar variables, then probably either [] or nan will work. If they are only being used for flags, then logical true/false would work and is probably the fastest. If there are arrays of them, then you are probably stuck with nan or logical. If you are processing arrays of them downstream in your code beyond just flag checking, many functions can automatically deal with and/or ignore the nan, so again nan might be your best choice.
Bottom line is I wouldn't worry so much about the efficiency of isempty( ) vs isnan( ) vs logical checking. I would pay more attention to how they will be used downstream in your code. Hard to advise any more than this without knowing more about what the code is doing.
1 Comment
Fawad Khan
on 21 May 2021
Steven Lord
on 20 May 2021
1 vote
In addition to what James and Walter have written, if you're writing your own class and want to be able to indicate that some element of an array of instances of your class are "missing" you could implement your class to satisfy the missing contract. If you do I recommend you write a test that it correctly satisfies the contract using the matlab.test.behavior.Missing class as the base class for that test.
1 Comment
Fawad Khan
on 21 May 2021
Bruno Luong
on 21 May 2021
0 votes
1 Comment
Fawad Khan
on 22 Nov 2021
Binbin Qi
on 21 Nov 2021
I think you can use class.empty for null in matlab
classdef A < handle
properties
empty = A.empty;
end
end
1 Comment
Fawad Khan
on 22 Nov 2021
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!