How can i read in a .txt file without the first column gets saved?
4 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Tatjana Mü
el 14 de Sept. de 2021
Respondida: Rik
el 14 de Sept. de 2021
Hallo,
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
anzahl_elemente=0;
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
rh_elem_neutral=anzahl_elemente;
end
if strcmp ('UO+',temp_string), break, end %UO+ is the last element in the row
end
[temp_string,neutral]=strtok(cellstr(element_cim),'()')
spalte_neutral=min(find(strcmp(neutral,'UO+')))
%Read the intensities
zeilen_nr=0;
fscanf(fid_in,'%*s',[1,1]); %Not save the first column
while feof(fid_in)==0
zeilen_nr=zeilen_nr+1;
for spalten_nr=1:anzahl_elemente
intens_cim(zeilen_nr,spalten_nr)=fscanf(fid_in,'%f',[1,1]);
fscanf(fid_in,'%*s',[1,1]); %Not save the first column
end
end
[anzahl_runs,anzahl_elemente]=size(intens_cim);
%Scrollwordfunction:
function scrollword(fid,n); % skips a word of 1 to n
for i=1 : n,
fscanf(fid,'%s',[1,1]);
end
0 comentarios
Respuesta aceptada
Rik
el 14 de Sept. de 2021
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 comentarios
Más respuestas (0)
Ver también
Categorías
Más información sobre Environment and Settings en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!