How to read specific row and column header from text file with csv format?

4 views (last 30 days)
I have a very large simulation result files and I want to plot it. I build a function that I can plot specific column I want. But there are something wrong.
So, I build a small file to test the code. I have a 'BERtest.txt' file that looks like this:
Offset,SNR,Block,rawBER,LDPCBER
0,13,1,-2.20410,-2.84498
0,13,2,-2.30101,-3.14601
0,13,3,-2.17608,-2.84505
0,13,4,-2.20411,-2.74816
0,13,5,-2.27983,-2.84507
Now, I have a simple function code like this:
%
function [head1,head2,x1,y1] = getdatatxt(filename,nx,ny)
fid = fopen(filename);
head1 = textscan(fid,'%s',1,'HeaderLines',0,'HeaderColumns',nx,'Delimiter', ',');
head2 = textscan(fid,'%s',1,'HeaderLines',0,'HeaderColumns',ny,'Delimiter', ',');
fclose(fid);
data = dlmread(filename, ',',1,0);
x1 = data(:,nx);
y1 = data(:,ny);
Suppose x data should be rawBER column and y should be LDPCBER column. In addition, h1 and h2 should show the name of its header. So, h1 and h2 should be 'rawBER' and 'LDPCBER'. Then, I execute this command:
%
[h1,h2,x,y]=getdatatxt('BERtest.txt',4,5);
The result is:
%
x =
-2.2041
-2.3010
-2.1761
-2.2041
-2.2798
y =
-2.8450
-3.1460
-2.8451
-2.7482
-2.8451
h1{1} =
'Offset'
h2{1} =
'SNR'
So YES, x and y are correct but I don't understand why h1 and h2 are wrong.
Anyone has an idea?
Thank you in advance.
kp

Accepted Answer

KL
KL on 21 Oct 2017
Why don't you just use readtable?
It's much more efficient and easier, it reads both data and headers and also stores them nicely in a table.
T = readtable('BERtest.txt');

More Answers (0)

Community Treasure Hunt

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

Start Hunting!