Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to textscan to read all the lines in a file

Tags:

matlab

I am trying to read all the lines in a .m file with the following

file_content = textscan(fid, '%s', 'delimiter', '\n', 'whitespace', '')

but this just returns

file_content = 

    {0x1 cell}

when actually my file has 224 line. so if i use

file_content = textscan(fid,'%s',224,'delimiter','\n')

i get all the lines

file_content = 

    {224x1 cell}

what will be a more proper way to read all the data(mostly strings) in a .m file? thanks

like image 961
learningMatlab Avatar asked Feb 19 '23 04:02

learningMatlab


2 Answers

Since you do not list your needs (are you reading a huge file?, many small files? is speed an issue? what do you really want to do?) I'm giving you the simplest possible answer:

You do this:

f = fopen('data.txt');             
g = textscan(f,'%s','delimiter','\n');
fclose(f);

remember to close after reading, because otherwise you won't be able to read again.

You can get the first line as g{1}{1}, the second as g{1}{2} and so on.

Here is the matlab documentation for textscan which gives a lot more details.

like image 130
carlosdc Avatar answered Feb 27 '23 23:02

carlosdc


Here's a method that worked for me:

fid = fopen('filename','r'); %opening in read mode (default)
inter = textscan(fid,'%[^\n]'); 
lines = inter{1,1};
fclose(fid);

This command reads the whole file 'line by line'. for example, I had a text file with 1332 lines, this code creates a variable inter which is a {1,1 cell} and lines which is a [1x102944 char].

I'm not sure why/how this works (it'd be great if someone else reading this knows how!) but it works for my program.

like image 41
Gautam Avatar answered Feb 27 '23 22:02

Gautam