Reputation: 1271
I have a .txt file in the format of:
123123 4
123234 4
515511 4
157888 4
854634 4
345661 4
I want to be able to import each column into a different variable. I've tried:
data = textscan(fid, '%f %*[^\n]','HeaderLines',0);
test = textscan(fid, '%*f %f %*[^\n]','HeaderLines',0);
Which successfully imports the first column of numbers however test
returns []
.
What is causing this?
Upvotes: 1
Views: 2753
Reputation: 25232
At the moment you're scanning the whole file two times - that's not a good idea.
So how about importing everything in one variable and splitting it up afterwards?
DATA = importdata('myFile.txt',' ',0)
data = DATA(:,1);
test = DATA(:,2);
clear DATA
Be aware that if you have headerlines, the code varies a little:
headerlines = 5
DATA = importdata('myData.txt',' ',headerlines)
data = DATA.data(:,1);
test = DATA.data(:,2);
If the white space delimiter ' '
is not working, try tabulator '/t'
.
The reason why your approach is not working is the file-ID fid
. Imagine fid
is a pack of tasty cheese. Every line of the file which got read by textscan is like you have eaten one slice of cheese. So after your command:
data = textscan(fid, '%f %*[^\n]','HeaderLines',0);
there is no cheese left. And your second textscan
call is left without any cheese. To make it work you would need to open another similar pack of cheese:
fid = fopen('myData.txt');
data = textscan(fid, '%f %*f %*[^\n]','HeaderLines',0);
fclose(fid)
fid = fopen('myData.txt');
test = textscan(fid, '%*f %f %*[^\n]','HeaderLines',0);
fclose(fid)
But I tell you, you will get fat. But if you really want to eat cheese, do it as follows:
fid = fopen('myData.txt');
DATA = textscan(fid, '%f %f %*[^\n]','HeaderLines',0);
fclose(fid)
data = DATA(1);
test = DATA(2);
Upvotes: 3