Why does not Matlab warn about type casting (double - uint8) or rounding

7 次查看(过去 30 天)
I read with textscan values from a CSV file, '%s%d%f%d', having four columns.
% file: 12345A;102;0.1312;1 [...]
I initalized matrix M (nan(#cols, #rows)) for some results to be computed from those values (3rd column). Then in a for-loop I made some calculations with my data (3rd column, several records). Then I saved my three numbers (mean, std, on/off value from 4th column in CSV) in a larger M matrix:
M(k, 3*m+[-2 -1 0]) = [value_mean value_std value_correct]; % e.g., M(2, [4 5 6]) = [0.1032 0.0812 1]
I got stuck because M matrix contained only integers even if all 'value_mean' and 'value_std' were non-integers.
M(2, [4 5 6]) % [0 0 1]
Only after a while I understood that textscan function reads '%d' as type 'int32', and then in the assignment (above) types of 'value_mean' and 'value_std' are magically / automatically casted to int or rounded. Matrix M itself was before and afterwards of type 'double'. Matlab didn't give any warning.
I wonder if it is possible to give a warning message in case of this kind of (necessary) casts? I understand that having no strong types brings this kinds of problems.

采纳的回答

Walter Roberson
Walter Roberson 2012-6-27
My answer in the past has been that it is because it happens so often in MATLAB. Consider for example,
K = uint8(0);
K = K + 1;
The second of those expressions is actually a mixed-mode operation, because "1" by itself refers to double precision.
The situation is unlike that of C (for example) or other strongly-typed languages that look at the declared type of K and then compile the "1" as being the appropriate type at compile time. Variables can change type in MATLAB, including in ways that are not obvious. For example, if you had the lines
K = uint8(0);
disp('hello');
K = K + 1;
then because disp might be overridden by a local disp.m at execution time, one cannot rule out the possibility that there might be a disp.m that includes assignin('caller', 'K', 0); -- a statement that assigns a double precision 0 to K, making the K = K + 1 into a double precision operation instead of an integer operation.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by