フィルターのクリア

How to read a file and write to a file?

1 回表示 (過去 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 Center および File ExchangeIntroduction 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