MATLAB Answers

How to add data from a text file to another text file ?

3 views (last 30 days)
Izem
Izem on 6 Oct 2020
Commented: Izem on 7 Oct 2020
Hello, I want to modify File 2 to File 3 based on File 1. As you can see in the picture attached to this question, some (m,n) values in File 1 does not exist in File 2 so I want to add them with a correction = 0 so that I can get File3.
I tried to write File 2 in a cell and then write it back with the added lines but I don't know how to do it correctly, Here is the first lines of my code if someone can help
mcorrection = str2double(C{1,1});
ncorrection = str2double(C{1,2});
correction = C{1,3};
data=readfile(name);
HeaderLines = 8;
for i=(HeaderLines+1):numel(data)
str=data{i};
vals=textscan(str,' %f %f %f %f %f %f %f %f');
m=vals{1}; n=vals{2};
for j=1:length(correction)
if m == mcorrection(j) && n == ncorrection(j)
A{j} = sprintf('%d %d %f',str2num(C{1,1}{j}),str2num(C{1,2}{j}),str2num(C{1,3}{j}));
else
A{j} = sprintf('%d %d 0.0',str2num(C{1,1}{j}),str2num(C{1,2}{j}));

  16 Comments

Izem
Izem on 7 Oct 2020
Hi, I made some corrections and now it does what I want, can we optimize it ?
HeaderLines = 8;
file1 = readfile('conf001_00630.00Hz.ray');
file2 = readfile('InputPidSidelinef630.dat');
A = [];
for i=(HeaderLines+1):numel(file1)
%store in temp variable
if isempty(file1{i}),continue,end
str1=file1{i};
vals1=textscan(str1,' %f %f %f %f %f %f %f %f');
m1=vals1{1}; n1=vals1{2}; numero=vals1{3};
if numero == 1
A = [A;[m1 n1]];
end
end
B = [];
for i=1:numel(file2)
%store in temp variable
if isempty(file2{i}),continue,end
str2=file2{i};
vals2=textscan(str2,' %f %f %f');
m2=vals2{1}; n2=vals2{2}; correction=vals2{3};
B = [B;[m2 n2 correction]];
end
for i=1:length(A)
for j=1:length(B)
if A(i,1)== B(j,1) && A(i,2)== B(j,2)
A(i,3) = B(j,3);
break
else
A(i,3) = 0;
end
end
end
fid = fopen('file3.dat','w');
for i = 1:length(A)
fprintf(fid,'%d %d %f \n',A(i,1),A(i,2),A(i,3));
end
fclose(fid);
Rik
Rik on 7 Oct 2020
The last nested loop can probably be replaced by ismember.

Sign in to comment.

Answers (0)

Community Treasure Hunt

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

Start Hunting!