extracting data from multiple txt files
Show older comments
Hello, I am writing a code to extract some data from multiple txt files from specific location and I am stuck at one step:
%loading all files in the folder
filedir= 'X:\GD\EA\ASP\Interest groups\TEST\targets';
files = dir(fullfile(filedir, '*.log'));
nfiles=length(files); %number of files in the specified folder
%HTLl=cell(nfiles, 8);
%HTLr=cell(nfiles, 8);
%TARGl=cell(nfiles,20);
%TARGr=cell(nfiles,20);
for i=1: nfiles
%F=files(i)
fid(i)=fopen(fullfile(filedir, files(i).name),'rt');
%fid=fopen(fullfile(filedir, files(i).name),'rt');
s{i}=textscan(fid(i), '%s', 'delimiter','\n');
for k= 1: nfiles
HTL(k)=s{1,(k)}{1,1}{8,1}
end
fclose(fid(i));
end
my s has the correct dimension but every s has three layers. When I try to extract HTL (last step) it gives me the error:
Unable to perform assignment because the indices on the left side are not compatible
with the size of the right side.
Error in loadTargets (line 36)
HTL(k)=s{1,(k)}{1,1}{8,1}
not sure how to fix this. I would appreciate some help!
K
Answers (1)
One obvious issue with your code is that it makes no sense to have the k loop inside the i loop. I suspect the k loop is meant to run after the i loop has terminated.
Note that s is going to be a vector, so you should be using 1d indexing not 2d. And the extra brackets around k are just clutter, so it should be s{k} not s{1, (k)}. The content of s{k} is going to be a scalar cell, so 2d indexing is once again misleading, s{k}{1} is simpler. And finally the content of s{k}{1} is going to be a vector again, so it should be s{k}{1}{8}. Note that s{k}{1}{8} is going to be a character vector, so assigning that to one element of a matrix is going to be an error. You could assign that to a cell array which seemed to be the intent with your commented out predeclaration of HTL (but why has it got 8 columns?)
So, possibly, your k loop should be:
%after the end of the i loop
HTL = cell(nfiles, 1);
for k= 1: nfiles
HTL{k}=s{k}{1}{8};
end
Note that if all you're trying to do is to extract just the 8th line of each file then there are much easier ways to do that.
Categories
Find more on Startup and Shutdown 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!