How to read a file and write to a file?

2 visualizaciones (últimos 30 días)
Ironmaniac
Ironmaniac el 28 de Nov. de 2016
Comentada: Ironmaniac el 29 de Nov. de 2016
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 comentario
Preethi
Preethi el 28 de Nov. de 2016
hi,
use can use file handling functions like fopen(), fprintf(), fscanf()

Iniciar sesión para comentar.

Respuesta aceptada

KSSV
KSSV el 28 de Nov. de 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 comentarios
KSSV
KSSV el 29 de Nov. de 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.
Ironmaniac
Ironmaniac el 29 de Nov. de 2016
Thank you.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Introduction to Installation and Licensing en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by