Unexpected behaviour of table2array
Show older comments
Documentation for table2array says, "table2array creates a homogeneous array, A, of the dominant data type. For example, if T contains double and single numeric data, table2array(T) returns an array with data type single." That surprises me. I would expect double to dominate single. Here is a simple example whose results surprise me:
function table2array_surprise
Dou = 2.345;
Int = int32(2);
T = table(Dou, Int);
R = table2array(T);
fprintf('Dou : %5.3f\n', Dou(1,1));
fprintf('R(1,1): %5.3f\n', R(1,1));
end
I encounter this using R2018a database select(). If the column is int in the database, it is Matlab int in the resulting table. table2array(select(...)) truncates other float(8) columns to integers.
Documented behavior, true, but surprising.
Answers (1)
Walter Roberson
on 20 Mar 2018
2 votes
This is consistent with the MATLAB type rules. When you mix numeric data types then the rule is that the result is the most restrictive data type. I do not know why that was chosen as opposed to least restrictive, but it is the rule even just for horzcat
4 Comments
George Corliss
on 20 Mar 2018
When you mix numeric data types then the rule is that the result is the most restrictive data type
It's a bit more complicated than that. See Valid combinations of unlike classes and the related topics in that page.
I can't remember where I read that but I believe the reasoning behind the implicit narrowing conversion was that if the user used single for some data it was on purpose, so better convert everything to single to follow that purpose. Never mind that a lot of people don't know what they're doing and that implicit narrowing conversion loses information.
It's certainly something difficult to adjust to when you come from other languages that only allow widening, non-lossy, conversions to be implicit.
Walter Roberson
on 20 Mar 2018
That table works out as character < integer < single < double with the left-most used in the expression being the result
Except, as per the links below the table, when you mix integers with or without float, the common type is the leftmost integer in the array
[single uint32 int8 double] -> all converted to uint32
[logical double int8 uint32] -> all converted to int8
Madness!
Categories
Find more on Tables 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!