Strange issue encountered using textscan and cell arrays

1 次查看(过去 30 天)
When I run the following snippet of code:
str = '(3.3940269999999999,1,0) (0,3.3940269999999999,0) (0,0,2.024902)';
format = '(%f, %d, %d) (%d, %f, %d) (%d, %d, %f)';
A = textscan(str, format);
matrix = [A{1,1}, A{1,4}, A{1,7} ; A{1,2}, A{1,5}, A{1,8}; A{1,3}, A{1,6}, A{1,9}]
I get the following output matrix =
3 0 0
1 3 0
0 0 2
Why were the floating point numbers converted to integers?

采纳的回答

Star Strider
Star Strider 2016-10-14
When I run a slightly modified version of your code (because format is a function that defines the format displayed in the Command Window and Tooltips), I get:
format_string = '(%f, %d, %d) (%d, %f, %d) (%d, %d, %f)';
A = textscan(str, format_string);
matrix =
3×3 int32 matrix
3 0 0
1 3 0
0 0 2
That is likely because of the '%d' format descriptors. Convert them to '%f':
format_string = '(%f, %f, %f) (%f, %f, %f) (%f, %f, %f)';
to get:
matrix =
3.394 0 0
1 3.394 0
0 0 2.0249

更多回答(1 个)

Eamon
Eamon 2016-10-14
I think if you use the format function like below before the rest of your code, it will show the original floating point numbers.
format long

类别

Help CenterFile Exchange 中查找有关 Data Type Conversion 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by