Importing data from text file with columns gives blank array

2 次查看(过去 30 天)
Hello,
I have a text file, call it 'test.txt', which is formatted as follows (first few lines):
% Model: modelname.mph
% X Y data
-2.4352193692676705E-5 -2.4323730047927036E-5 2.4407735112883654E-15
-2.5E-5 -2.4000000000000004E-5 4.924835274917804E-16
-2.5E-5 -2.5E-5 8.670778241812167E-17
-2.3999999999999957E-5 -2.5E-5 8.811128321077918E-16
-2.425773709270738E-5 -2.349487305489201E-5 6.031906610009718E-16
-2.5E-5 -2.3000000000000007E-5 4.580917112816902E-16
-2.2999999999999953E-5 -2.5E-5 7.858031671847371E-16
-2.350325428571997E-5 -2.4123801341378673E-5 1.2541461148846415E-15
-2.4220908928270087E-5 -2.2505897573838E-5 7.091675640817479E-16
-2.5E-5 -2.200000000000001E-5 5.006064907801435E-16
-2.2459486457791532E-5 -2.4198191977146302E-5 9.858070355554836E-16
-2.1999999999999955E-5 -2.5E-5 5.382206567387998E-16
Basically the X and Y columns correspond to a 2d grid, and the data column is the value at that point on the grid. Ultimately I want to make a 2d color plot with this data. To import it I have the following:
fileID = fopen('test.txt');
formatSpec = '%f %f %f';
A = cell2mat(textscan(fileID,formatSpec));
fclose(fileID);
The code runs, but gives me an empty 0x3 array. This seems like it should be very simple, but I am just missing something. Any help would be greatly appreciated.

采纳的回答

Star Strider
Star Strider 2018-11-9
Without having the file, it is difficult to say. The first two header lines are commented out in your post. If they are present in your actual file (with or without the ‘%’ signs), adding 'HeaderLines' to the argument list could work:
In = textscan(fileID,formatSpec, 'HeaderLines',2, 'CollectOutput,1);
fclose(fileID);
A = cell2mat(In);
I would break the textscan and cell2mat calls out into separate lines. This allows you to see what textscan is producing first.
  2 个评论
the_visitor
the_visitor 2018-11-9
Ah, it was the HeaderLines argument that did it. The program that I exported that data from automatically commented out the first two lines, and I just assumed that Matlab would treat it as such, but now that I think about it there is no reason why it should do so since a text file is just a text file. Well, I feel silly now.
Anyway, thanks a bunch for your help!
Star Strider
Star Strider 2018-11-9
As always, my pleasure!
No worries. I am sure the program you exported the data from meant well.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Data Import and Export 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by