Ho to separate multiple files into individual columns?

1 view (last 30 days)
I have a folder containing 160 .txt files and need to pull them into a matlab matrix and then into vectors. Each file contains a review string which has already been converted into single words per row(e.g. Is this a sentence? becomes
'Is' 'this' 'a' 'sentence' 'QUESTION_MARK')
What I am trying to do is pull the documents into Matlab and then each word for the file will shown in rows and then each document carried over to the next column. The code I have does pull in the documents and every line of text for all 160 files from the selected folder but it lists al the data down one column where I need to have one file to a column. I know there is a way to do this but I cannot seem to find a solution that works with my code.
if true
fpath = ('C:\Users\Willem\Documents\MATLAB\fold1');
files = dir(fullfile(fpath,'*.oneline'));
nfiles = length(files);
data = [];
for k = 1:nfiles
data = [data; importdata(fullfile(fpath,files(k).name))];
end
end
Any and all help will be very much appreciated.

Accepted Answer

Walter Roberson
Walter Roberson on 8 Nov 2013
MATLAB arrays cannot have varying number of rows per column. The closest you can get would be to use empty elements as placeholders.
data = {};
for k = 1 : nfiles
thisdata = importdata(fullfile(fpath,files(k).name);
nrow = length(thisdata);
if size(data,1) < nrow
data(nrow,1) = {}; %extend number of rows if needed
end
data(1:nrow,end+1) = thisdata(:); %add on the new info
end
  1 Comment
Willem
Willem on 9 Nov 2013
Thank you very much Walter your help was really useful. My code is now working exactly as I has envisioned it would. each document is displayed in separate columns. I was having a error throwback for the if statement though but I simply removed it altogether and the code worked perfectly. Thank you again.

Sign in to comment.

More Answers (0)

Categories

Find more on MATLAB 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!