Insert two text lines in the blank rows of a txt file

2 views (last 30 days)
I have to insert two different text rows in the blank rows of the attached txt file. How should I proceed?
  4 Comments
KSSV
KSSV on 7 Dec 2021
You can use fprintf in the loop where you are generating the data. Give a condition and put text when condition is met. Read about fprintf.

Sign in to comment.

Answers (1)

Jan
Jan on 7 Dec 2021
Edited: Jan on 7 Dec 2021
You cannot insert text in files, because a file an grow at its end only. There is no operation to shift the contents of a file.
You have to import the file at first, insert the data, and recreate the file. Prefer an import as text to avoid rounding effects with the limited precision of the input.
By the way, this can be simplified:
dataset_red(y+10,:)=NaN*ones(1,6);
% Version 1:
dataset_red(y+10,:) = NaN(1,6);
% Version two using Matlab's expanding of scalars:
dataset_red(y+10,:) = NaN;
This will not work:
for i=1:length(dataset)
...
if <anycondition>
i = length(dataset)
end
end
Matlab's for command does not care about the value of the counter. See:
for k = 1:5
disp(k)
k = 17;
end
% This prints: 1 2 3 4 5
Either convert the loop to a while loop or use break to stop the loop.
if start==0
dataset_red(1,:)=NaN*ones(1,6);
dataset_red(2,:)=NaN*ones(1,6);
start=1;
elseif isnan(dataset(i,1))==0 && start>0
After you have excluded the case start==0 already, there is no need to check for start>0 again.
  2 Comments
Emilio Pulli
Emilio Pulli on 7 Dec 2021
ok thank you man but the main problem of inserting the text lines remain....
Emilio Pulli
Emilio Pulli on 7 Dec 2021
I figured it out by manipulating te string matrix S in this way:
%% [...] The code previously typed till the creation of string matrix S
flag=0;
for i=1:size(S,1)
for j=1:1:size(S,2)
if ismissing(S(i,j))==1 && j==1 && flag==0
S(i,j)={'Variables = v_wind[m/s],omega[rpm],Cp,Cm,P[W],M[Nm]'};
flag=flag+1;
end
if ismissing(S(i,j))==1 && flag==1 && j==1
S(i,j)={['ZONE T = “V wind =',num2str(S(i+1,1)),'[m/s]”']};
flag=0;
end
end
end
writematrix(S, 'dataset_red.txt', 'delimiter', 'tab');

Sign in to comment.

Categories

Find more on Characters and Strings 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!