How to read only some columns of a text file?

I'd like to read out only columns from 3 to 7. However, this is not working. Can you help?
Thanks!
%Get events from text file
prompt_totalfiles = 'Enter number of files you want to input: '; %asks for number of files
total_files = input(prompt_totalfiles);
fileids = cell(total_files,1);
j = 1;
Baseline_adjustment = 0.1; %put in baseline photodetector value here (the readout with the led on but the patch cable in pitch black
wholedff = cell(1, 11);
for file = 1:total_files
[inputfile,path] = uigetfile('*.txt');
fileids{file} = fopen(fullfile(path, inputfile));
if fileids{file} == -1
error('Failed to open file "%s"', fullfile(path, inputfile));
end
b = textscan(fileids{file},'%*n %*n %n %n %n %n %n', 'delimiter', '/t');
num = b{3};
epochn = b{4};
state = b{5};
count = b{6};
duration = b{7};

1 Comment

'delimiter', '\t'
Also if columns 1 and 2 might not be numeric then use %*s for them.

Sign in to comment.

Answers (1)

The text file might have more than 7 coloums.
Replace
'%*n %*n %n %n %n %n %n'
by
'%*s%*s%n%n%n%n%n%*[^\n]'
%*[^\n]' skips to the end of line
The code doesn't include end to close the for-loop.
The result of the import might be overwritten for each iteration of the loop.

8 Comments

The text file has 7 columns, and the fifth is non-numerical! This:
'%*s%*s%n%n%n%n%n%*[^\n]'
gives me the same error.
Index exceeds the number of array elements (5).
Error in SocialTest (line 21)
count = b{6};
Still gives me the same error... I really don't get what's going on.
Why would you expect it to have 6 elements, when you only ask to read in 5 columns?
When you use %*s then that does not mean that it should insert an empty array at that point in the output sequence: it means that those values are not output at all. You skip two input columns, so input column 6 is the 4th column of what is saved.
Of course, stupid mistake! Thanks!
Now the only problem seems to be that by using %s on the fifth column, it reads for the first row not only NR, but also 2 and 20; second row, not only W, but also 94 and 940. So basically it takes the sixth and the seventh column and it reads them in the fifth.
Please upload a sample file (in exactly the same format you are using)
Ah no I actually found out the problem! I should use %2s instead of %s. Thanks!
" [...] I should use %2s instead of %s." No, the problem is rather with the delimiter. I assume there is no '\t' after the six coloumn.

Sign in to comment.

Categories

Asked:

on 11 May 2020

Commented:

on 11 May 2020

Community Treasure Hunt

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

Start Hunting!