Clear Filters
Clear Filters

Importing data from text file with columns gives blank array

3 views (last 30 days)
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.

Accepted Answer

Star Strider
Star Strider on 9 Nov 2018
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 Comments
the_visitor
the_visitor on 9 Nov 2018
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 on 9 Nov 2018
As always, my pleasure!
No worries. I am sure the program you exported the data from meant well.

Sign in to comment.

More Answers (0)

Categories

Find more on Data Import and Export in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!