How to read a string from a text file as a string in Matlab?

I am trying to read a text file in MATLAB, which has the following format. I am looking to read the entire string as a string.

2402:0.099061 2404:0.136546 2406:0.447161 2407:0.126333 2408:0.213803 2411:0.068189 

I tried a couple of things.

textscan(fid, '%s') reads the line, but breaks the line into cells in spaces.

fscanf(fid, '%s') reads a string as a string, but removes all spaces.

+4
source share
5 answers

fgetl(fid) will do what you are looking for. New line is disabled.

+8
source

textscan uses a space separator by default. Set the separator to an empty line:

 >> q = textscan(fid, '%s', 'Delimiter', ''); >> q{1}{:} ans = 2402:0.099061 2404:0.136546 2406:0.447161 2407:0.126333 2408:0.213803 2411:0.068189 
+2
source

If you want to read the entire file as a line (your file has only one line), try:

 s = fileread('input.txt'); %# returns a char vector s = strtrim(s); %# trim whitespaces 

If you look at the source code of the FILEREAD function, it basically reads the file in binary mode as an array of characters: fread(fid, '*char')

+1
source

space is treated as the default delimiter using textscan. specify another separator (which is not in your data) when calling which should do the trick, add this fe

  'delimiter', '|' 

you can also use

  file = textread(<fileref goes here>, '%s', 'delimiter', '\n') 

then

  file{1,1} 

will return

  ans = 2402:0.099061 2404:0.136546 2406:0.447161 2407:0.126333 2408:0.213803 2411:0.068189 

hope this helps

0
source

Using:

 clc; fid = fopen('fileName.m'); while ischar(tline) disp(strcat("Line imported: ",tline)) tline = fgetl(fid); end fclose(fid); 
0
source

Source: https://habr.com/ru/post/1415636/


All Articles