You are now following this question
- You will see updates in your followed content feed.
- You may receive emails, depending on your communication preferences.
How to read line by line a cell file (3x1) using a loop?
4 views (last 30 days)
Show older comments
Hello,
I have a .txt file. I use the command
regexp(fileread('file1.txt'), '\r?\n', 'split') .';
in order to open it. This file contains 3 lines (it is a 3x1cell). I would like to read line by line each line of this file, by using a loop.
Could anyone help me?
Accepted Answer
Ameer Hamza
on 14 Apr 2020
Edited: Ameer Hamza
on 14 Apr 2020
For-loop version
fid = fopen('test.txt');
data = {};
while true
line_data = fgetl(fid);
if line_data == -1
break;
end
data{end+1} = line_data;
end
data = data';
fclose(fid);
18 Comments
Ivan Mich
on 14 Apr 2020
ok thank you first of all. My qestion is how could i do this by taking only 1st,2nd 3rd line. Eg
I read a file via readtable. From this file I want to take only the two columns of each line.as a result I use commands
t=readtable('test.txt', 'readvariablenames', true);
o=t{:,2:3}
"o" shows me all lines of two columns I want to use. My question is how I could define the 1st, 2nd and 3rd line separetale by a loop?
Ameer Hamza
on 14 Apr 2020
I couldn't understand the question. Can you attach a small example txt file and show the expected output.
Ivan Mich
on 14 Apr 2020
of course,
Well my .txt file :
point V1 V2 V3 V4 V5 V6 V7
s1 22 36 1 0 5 6 5
s2 47 35 1 0 5 6 5
s3 33 225 1 0 5 6 5
By using o=t{:,2:3} I read all lines of 2nd and 3rd column, I mean
22 36
47 35
33 225
I would like to use a command in order to read 1st,2nd and 3rd line separately.
Ameer Hamza
on 14 Apr 2020
You already have data in variable 'o'. Do you want to read the data in seperate variables?
t=readtable('Files3.txt', 'readvariablenames', true);
o1 = t{:,1};
o2 = t{:,2};
o3 = t{:,3};
Note that in MATLAB, it is recommended not to create separate variables for each column. It is recommended to extract data from the table using indexing.
Ivan Mich
on 14 Apr 2020
By using your solution I can see only value: 22,
I would like to take
o1= 22 36
o2= 47 35
o3= 33 325
How could I take it?
Ameer Hamza
on 14 Apr 2020
Ok. I get it now. Please try
t=readtable('Files3.txt', 'readvariablenames', true);
o1 = t{1,2:3};
o2 = t{2,2:3};
o3 = t{3,2:3};
Ivan Mich
on 14 Apr 2020
οκ , Thank you. May I ask you something ? If I want to use a loop, when I use
for i=1:numel(o)
and when
for i=1:nrows(o)
?
Which is the most correct?
Ameer Hamza
on 14 Apr 2020
The method with for loop is quite messy if you want to use different variable names
t=readtable('Files3.txt', 'readvariablenames', true);
o1 = zeros(1,2);
o2 = zeros(1,2);
o3 = zeros(1,2);
for i=1:size(t,1)
for j=2:3
if i==1
o1(j-1) = t{i,j};
elseif i==2
o2(j-1) = t{i,j};
elseif i==3
o3(j-1) = t{i,j};
end
end
end
The same can be done with the following code, but it uses eval(), which is highly unrecommended (or borderline prohibited).
t=readtable('Files3.txt', 'readvariablenames', true);
for i=1:size(t,1)
eval(sprintf('o%d=t{%d,2:3};', i, i));
end
Ivan Mich
on 14 Apr 2020
Οκ , thank you. The reason I am asking you these questions is that I want to make a code for a problem
Imagine that I have File3.txt, File2.txt and one .exe file (lets call it my.exe). File3.txt has my data, File2.txt is the input of my.exe(input that is needed in order to execute my.exe).
I would like from file3 to take only one line and put in a specific line of the file2(input). After putting this line in file2 I can run my exe file. The problem is that File 3 obtain many lines. I want to use o for loop in order to run my .exe file for all the lines separately of file3 (I mean I would like to take the first line of 2nd and 3rd column from file 3, put this line to file2, run my.exe file and take my results. After that I would like to take the second line of 2nd and 3rd column from file 3, put this line to file2, run my.exe file and take my results. After all this repeatability I would like to the last line of 2nd and 3rd column of file 3 put this line to file2, run my.exe file and take my results.)
I have to mention that I want after each repeatability the name of input file (File2.txt) does not change, inspite of the different content.
I wrote some commands but I can't continue it to composition.
%for
% for j= 1: size{lines_to_replace_with,1}
%
% line_to_replace_withnew = sprintf('%g\t%g',lines_to_replace_with(j));
% end
t3 = readtable('Files3.txt', 'readvariablenames', true);
nrow = size(t3,1);
lines2 = regexp(fileread('File2.txt'), '\r?\n', 'split') .';
for K = 1 : nrow
line_to_replace_with = sprintf('%g\t%g',t3{K,2:3});
replaced_lines = [lines2(1:2); line_to_replace_with; lines2(4:end)];
newfilename = sprintf('newfile%d.txt', K);
fid = fopen(newfilename, 'wt');
fprintf(fid, '%s\n', replaced_lines{:});
fclose(fid);
end
system('my.exe <File2.txt')
Do you have any idea?
Ameer Hamza
on 14 Apr 2020
You already got the idea of getting information out of file3. The easiest way I can think of is to load the entire file2.txt, split it into lines, and insert the data at the required location. Then save the new data in file file4.txt and input file4.txt to the my.exe.
Ivan Mich
on 14 Apr 2020
Excuse me but I am confused, because I have tried the previous code and it works only for the first line of the data of File3.txt. My biggest problem is that I can not compose the loop that my code needs in order to make it run and take the results that I want. I would appreciate it if you could tell me how to run my script because I am really confused...
Ameer Hamza
on 15 Apr 2020
Ivan, can you attach two files txt (preferably with the minimum number of lines to explain the concept). Also, explain what do you want the content of file2.txt after each iteration. It will make it easy for me to suggest a solution. Right now, I can only guess the required behavior, and it may not be what you want at the end.
Ivan Mich
on 15 Apr 2020
of course. I will upload these two files: "File2.txt" is the input of the my.exe file. and "Files3.txt" has my data. I would like to take numbers of 2nd and 3rd column of first line of "Files3.txt" and put it to line3 of File2.txt. File2.txt is the input of .exe file. That' s why I use commands
line_to_replace_with = sprintf('%g\t%g',t3{K,2:3});
replaced_lines = [lines2(1:2); line_to_replace_with; lines2(4:end)];
newfilename = sprintf('newfile%d.txt', K);
fid = fopen(newfilename, 'wt');
fprintf(fid, '%s\n', replaced_lines{:});
fclose(fid);
after making this replacement I would like execute the .exe file , that's why i use command
system('my.exe <File2.txt')
After execiting this programm (I mean "my.exe" file) I would like to take numbers of 2nd and 3rd column of second line of Files3.txt and put it to line3 of File2.txt. After replacement I would like execute the .exe file and taking my results (and save them)
After that, I would like to take numbers of 2nd and 3rd column of third line of Files3.txt and put it to line3 of File2.txt. After replacement I would like execute the .exe file and taking my results (and save them).
I have to mention that I want after each repeatability the name of input file (File2.txt) does not change, inspite of the different content (and save them).
To be more spesific, for the first iteration File 2 has this content:
there are several values
the problem is
22 36
there are several values
the problem is
there are several values
the problem is
For the second iteration File2.txt has this content:
there are several values
the problem is
47 35
there are several values
the problem is
there are several values
the problem is
And for the third and the last iteration File2 has this content:
there are several values
the problem is
33 225
there are several values
the problem is
there are several values
the problem is
I wrote some commands but I can't continue it to composition of the loop I would like to make.
I have to mention that it is very important to keep the name of "File2.txt" as "File2.txt" , I mean that the name does not have to be changed.
I hope I help you with my explaination.
Ameer Hamza
on 16 Apr 2020
Try this. There might be a more efficient way to read and write the file, but this is the simplest way I can think of.
data_f3 = readtable('Files3.txt');
data_f3 = data_f3{:, 2:3};
for i=1:size(data_f3,1)
f = fopen('File2.txt', 'r');
data_f2 = textscan(f, '%s', 'Delimiter', '\n');
fclose(f);
data_f2 = data_f2{1};
data_f2{3} = num2str(data_f3(i,:));
f = fopen('File2.txt', 'w');
fprintf(f, '%s\n', data_f2{1:end-1});
fprintf(f, '%s', data_f2{end});
fclose(f);
system('my.exe < File2.txt')
end
Ivan Mich
on 19 Apr 2020
Ok , thank you first of all. Also I would like to ask something more. Files3.txt has a 4th column right (this column has numbers content). Could I use command if in order to read line by line the numbers of 4th column and after that to replace sepcific numbers?
to be more specific, I would like to put specific lines in input file, depending on the number of 4th column?
Is there a way to put command if after command
for i=1:size(data_f3,1)
???
for example I would like to ewrite:
if data_f3{:,4}==0
do something
else
do something
end
could you help me?
Ameer Hamza
on 19 Apr 2020
Your idea seems to be correct. My code already shows how to replace the line in file2.txt. You can use an if-else block to decide what you want to do based on the element in the fourth column.
Ivan Mich
on 19 Apr 2020
ok, my question is do I have to put an extra for ?
i mean
for i=1:size(data_f3,1)
for ii=1:size(data_f3{:,4},1)
if data_f3{:,4}==0
do something
else
do something
end
end
end
or it is not necessary because the number of lines is the same?
Do you understand what I mean?
Ameer Hamza
on 19 Apr 2020
I think using single for loop should be fine. Something like this
for i=1:size(data_f3,1)
if data_f3{i,4}==0
do something
else
do something
end
end
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!An Error Occurred
Unable to complete the action because of changes made to the page. Reload the page to see its updated state.
Select a Web Site
Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .
You can also select a web site from the following list
How to Get Best Site Performance
Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.
Americas
- América Latina (Español)
- Canada (English)
- United States (English)
Europe
- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)
- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- Switzerland
- United Kingdom (English)
Asia Pacific
- Australia (English)
- India (English)
- New Zealand (English)
- 中国
- 日本Japanese (日本語)
- 한국Korean (한국어)