How to read a file and write to a file?
2 views (last 30 days)
Show older comments
The input .txt file has 1000s of rows like:
.......................
.......................
43218680 102.485 1.1488100498592582e+07 10
43218700 102.201 1.1488148531592581e+07 12
43218740 102.536 1.1488244644592581e+07 12
43218760 102.615 1.1488292688592581e+07 10
43218720 102.289 1.1488196602592580e+07 10
......................
......................
I need help writing a MATLAB code that would read from the file to write to multiple .txt files for every unique value in the last column (here 10 and 12, known beforehand). In this case there need to be two .txt output files. The first .txt file will have
.........................................
43218680 102.485 1.1488100498592582e+07 10
43218760 102.615 1.1488292688592581e+07 10
43218720 102.289 1.1488196602592580e+07 10
..............................................
The second output .txt file should have the rows
..........................................
43218700 102.201 1.1488148531592581e+07 12
43218740 102.536 1.1488244644592581e+07 12
.............................................
An equivalent C code that worked is
....................................
#include<stdio.h>
#include<stdlib.h>
main()
{ int m,s;
float p;
double c;
FILE *fp,*fp1,*fp2;
fp=fopen("3Mar.txt","r");
fp1=fopen("10.txt","w");
fp2=fopen("12.txt","w");
/* 565216000 95.611 4.9407952477976400e+06 24 */
while(fscanf(fp,"%d %f %lf %d",&m,&p,&c,&s)!=EOF)
{
if(s==10)
{
fprintf(fp1,"%d %f %lf \n",m,p,c);
}
if(s==12)
{
fprintf(fp2,"%d %f %lf \n",m,p,c);
}
}
}
........................
Please help. A sample input file is attached.
1 Comment
Accepted Answer
KSSV
on 28 Nov 2016
data = importdata('data.txt') ;
% last column
c = data(:,end) ;
% get repeated numbers
[rc,ia,ib] = unique(c) ;
for i = 1:length(rc) ;
k = c(c==rc(i)) ;
fname = strcat(num2str(rc(i)),'.txt') ;
save(fname,'k','-ascii') ;
end
24 Comments
KSSV
on 29 Nov 2016
clc; clear all ;
data = importdata('data.txt') ;
% last column
c = data(:,end) ;
% get repeated numbers
[rc,ia,ib] = unique(c) ;
for i = 1:length(rc) ;
idx = find(c==rc(i)) ;
k = [idx data(idx,:)] ;
fname = strcat(num2str(rc(i)),'.txt') ;
% save(fname,'k','-ascii') ;
dlmwrite(fname,k)
end
All the above was easy job..by this time you should have learned it. No more discussion. This question is closed.
More Answers (0)
See Also
Categories
Find more on Entering Commands in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!