MATLAB Answers

How can i read in a .txt file without the first column gets saved?

조회 수: 6(최근 30일)
Tatjana Mü
Tatjana Mü 2021년 9월 14일
답변: Rik 2021년 9월 14일
I want to read text files. In the first row are the elements, in the following rows the measurement results. The first column contains the time. This column is not needed and should therefore not be read or saved. My script works except it only reads every second column. So instead of skipping the first column, it deletes every second. Can someone help me find the mistake?
Thank you for your help
%The first row with elements should be read in
clear intens_cim
while 1 anzahl_elemente=anzahl_elemente+1;
scrollword(fid_in,1); %Scrollword function should delete the first word
temp_string=fscanf(fid_in,'%s',[1,1]); element_cim(anzahl_elemente,1:length(temp_string))=temp_string;
if strcmp ('[103Rh]+',temp_string) %Rh for intern calibration
if strcmp ('UO+',temp_string), break, end %UO+ is the last element in the row
%Read the intensities
fscanf(fid_in,'%*s',[1,1]); %Not save the first column
while feof(fid_in)==0
for spalten_nr=1:anzahl_elemente
fscanf(fid_in,'%*s',[1,1]); %Not save the first column
function scrollword(fid,n); % skips a word of 1 to n
for i=1 : n,

채택된 답변

Rik 2021년 9월 14일
I prefer not to mix tasks. I first read my file, then I do the processing. It is generally a lot easier to remove parts of char arrays than to mess with fscanf to move the file pointer.
You can get my readfile function from the FEX. If you are using R2017a or later, you can also get it through the AddOn-manager. That will allow you to read a file to a cellstr, which you can then process with a simple loop. On R2020b or newer you can also use readlines instead.
The advantage of this setup is that every block of code has a clear purpose. Your current code has two jobs: reading the file, and while reading it, it should also be aware of the contents of the file and deal with that. Such a setup makes code confusing and difficult to debug and maintain.

추가 답변(0개)

Community Treasure Hunt

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

Start Hunting!

Translated by