Read data in Matlab

21 views (last 30 days)
Yro
Yro on 29 Aug 2019
Commented: madhan ravi on 9 Sep 2019
Hi, how can I read and plot data from a file in Matlab. I have the following data format:
# Axial
0.26889788E+11
0.89731269E+11
0.15931918E+15
0.20239994E+15
0.24342588E+15
0.28013145E+15
...
I have used the textscan function but I have not been able to obtain results. I tried something like this:
fileID = fopen ('/path/to/textfile', 'r+');
data = textscan (fileID, %f%f);
celldisp(data)
but I get an empty array
data = [ ]
Regards, thanks in advance.
  2 Comments
Rik
Rik on 29 Aug 2019
To avoid confusion, did you use this code, or did you actually use data=textscan(fileID,'%f%f');?
As for you question, you need to skip the first line in your processing. It would also help if you provided a sample file so it is possible to write code that works for your data.
dpb
dpb on 29 Aug 2019
The headerline would cause failure with the format string either way...
data = cell2mat(textscan(fileID, '%f%f',headerlines',1);
You might look at importdata(); it will handle simple file structures such as this automagically for you.

Sign in to comment.

Answers (1)

Kritika Bansal
Kritika Bansal on 9 Sep 2019
Hi,
Assuming that you are using MATLAB R2006a or above, you have the following options to read a text file in matlab:
  1. Using textscan()
fid = fopen('data.txt', 'rt'); %opens the file
data = textscan(fid, '%f%f', 'HeaderLines', 1); %skips the first line
ar = data{1}; %retrieves the column vector
2. Using readmatrix()
data = readmatrix('data.txt', 'NumHeaderLines', 1); %reads the data in column vector
3. Using importdata()
y= importdata('data.txt','',1); %reads the data as a structure into 3 fields
ar = y.data; %retrieves the column vector
You can find the documentation link of these functions below:
  1 Comment
madhan ravi
madhan ravi on 9 Sep 2019
Also readtable() is a good option.

Sign in to comment.

Categories

Find more on Data Import and Export 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!