How to read a file and write to a file?

조회 수: 2 (최근 30일)
Ironmaniac
Ironmaniac 2016년 11월 28일
댓글: Ironmaniac 2016년 11월 29일
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
Preethi
Preethi 2016년 11월 28일
hi,
use can use file handling functions like fopen(), fprintf(), fscanf()

댓글을 달려면 로그인하십시오.

채택된 답변

KSSV
KSSV 2016년 11월 28일
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
KSSV
KSSV 2016년 11월 29일
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.
Ironmaniac
Ironmaniac 2016년 11월 29일
Thank you.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Introduction to Installation and Licensing에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by