Is there a way to read only two columns of a file with textscan?

조회 수: 26 (최근 30일)
%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',-1, 'delimiter', '/t');
events = b{1};
event_times = b{2};
I am trying to use this code to read in only the first two columns of the text file. However, it doesn't seem to work: what I obtain is a 1x2 cell with [3;1] in the first column and [819;0] in the second one.
Instead, it should be [3; 3; 2; 1; 4; 5; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0] and [819; 826; 2279; 3427; 3907; 3919; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0; 0].
Thanks!

채택된 답변

Star Strider
Star Strider 2020년 5월 1일
There are 7 columns in the file image you posted. You can ignore a specific column by putting a * between the % and the descriptor.
Try it with this example (to read only the first 2 columns):
b = textscan(fileids{file},'%n %n %*n %*n %*n %*n %*n',-1, 'delimiter', '/t');
This will not fill the unread columns with 0, it will simply ignore them.
I do not have your file to test this with, so you may need to experiment to get it to do what you want.
See formatSpec for a full discussion.
  댓글 수: 4
Samuele Bolotta
Samuele Bolotta 2020년 5월 1일
As for the -1, I honestly have no idea since my job is precisely to try and make more efficient all of this stuff that was written by a previous person at the lab - whom I don't know. Anyway, I've tried: a) with b) without the -1 c) changing the '/t': I still got the same output: a 3 and a 819.
But by doing this:
b = textscan(fileids{file},'%n %n %*[^\n]', -1, 'delimiter', '\t', 'EndOfLine','\r\n');
I solved the issue and it now works!
This gives me the same correct results:
b = textscan(fileids{file},'%n %n %*[^\n]', 'delimiter', '/t');
So adding
"%*[^\n]"
is what really made the difference, even tho I'm not sure why what you originally proposed affects reading in the other rows. I attached the file anyway. Thanks!
Star Strider
Star Strider 2020년 5월 1일
As always, my pleasure!

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

darova
darova 2020년 5월 1일
Read whole data using importdata or readtable and choose only columns you want

카테고리

Help CenterFile Exchange에서 Data Import and Export에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by