How to keep false as false, and not as zero
Ältere Kommentare anzeigen
I want a vector that is laid out like below:
V=[false,false,false,false,x] ;
When the cell is not "false", I want it to take the value that it is (in this case x) and do something with it, but don't do anything if false. My problem comes from the fact that x can be 0, and that MatLab changes the values "false" to be "0". I can't have 0 instead of false, it has to be distinct.
The workaround currently is a data structure like follows:
V.element=[0,0,0,0,1];
V.value=[0,0,0,0,0];
Therefore, it sees if V.element is 1, and if so, checks V.value, otherwise it skips. This is fine, but just awkward to have to change twice as many values when changing the inputs of the function.
Tl;dr : MatLab makes false into a 0. Stop it MatLab; bad MatLab!
Akzeptierte Antwort
Weitere Antworten (1)
All the data in the array V must be the same data type. If x is not a logical array, the logical data will be converted to the class of x as shown in the table on this documentation page. This has been the behavior of MATLAB probably since support for logical data was added.
You could have V convert x into logical data, but you probably wouldn't want that either.
x = 2;
V = [false false false false logical(x)]
What exactly is your use case where you're trying to be able to distinguish false and 0 in the same array?
5 Kommentare
Walter Roberson
am 7 Nov. 2022
More generally it is not possible to store two different data types at the same level of the same array, except that if you define your own handle class derived from MixIn then you can (so for example you can have a vector of handles to graphics objects with mixed types)
You can create a cell array and store each element in its own cell, and that will preserve types, but this will take much more memory and will not allow straight-forward mathematical operations.
Steven Lord
am 7 Nov. 2022
The "MixIn" to which you refer is the matlab.mixin.Heterogeneous class. If you have a class hierarchy with base class that inherits from that class, you can have instances of two or more subclasses in the same array (whose class will be reported as their common base class) while each remains an instance of its subclass.
But neither double nor logical are subclasses of matlab.mixin.Heterogeneous.
Walter Roberson
am 7 Nov. 2022
Thanks, that's a good link. Looks like it does not need to be derived from handle.
George Smith
am 10 Nov. 2022
George Smith
am 30 Nov. 2022
Kategorien
Mehr zu Data Type Conversion finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!