Importing text files into matlab in order to manipulate the data
2 views (last 30 days)
Show older comments
Jamie Smith
on 11 Oct 2015
Commented: Walter Roberson
on 11 Oct 2015
Hi All,
I am very new to coding and so am having particular issues regarding importing text files to matlab so I can manipulate the data.
There are 113 text files each contain public information about a company in the following format
Sainsburys,18.810,78.920,99.001,5.808,41.202,56.078,18.004,75.000
the numbers represent certain characteristics. All the text files have eight numbers and the format is the same for them all.
I need to be able to create a table with all of the information together and then be able to analyse the data. My mine concern at the moment is importing all the data into one table that I can then work off.
Some of the coding I have used involved the use of 'dir' but the result of this is that it just tells me how many text files I have.
Any help would be much appreciated, thanks.
0 Comments
Accepted Answer
Walter Roberson
on 11 Oct 2015
For each file name that is found use
fid = fopen(CompleteFileName, 'rt');
datacell = textscan(fid, '%s%f%f%f%f%f%f%f%f', 'Delimiter', ',');
fclose(fid);
Then datacell{1} would be a cell array of strings that held the first column, datacell{2} would be a numeric column vector holding the second column, and so on through datacell{9} holding the 8th numeric column.
Here CompleteFileName is the fully qualified file name you extracted by using dir() and fullfile
3 Comments
Walter Roberson
on 11 Oct 2015
projectdirectory = 'C:\MyData\FlyingPigs';
dinfo = dir( fullfile(projectdirectory, '*.csv') );
for K = 1 : length(dinfo)
thisfile = dinfo(K).name;
CompleteFileName = fullfile(projectdirectory, thisfile);
fid = fopen(CompleteFileName, 'rt');
datacell = textscan(fid, '%s%f%f%f%f%f%f%f%f', 'Delimiter', ',');
fclose(fid);
do something with the information in datacell at this point
end
Walter Roberson
on 11 Oct 2015
By the way, you would get NaN if your files have header lines. But you didn't mention any header lines...
More Answers (0)
See Also
Categories
Find more on Standard File Formats 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!