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

3 次查看(过去 30 天)
I have to insert two different text rows in the blank rows of the attached txt file. How should I proceed?
  4 个评论
KSSV
KSSV 2021-12-7
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.

请先登录,再进行评论。

回答(1 个)

Jan
Jan 2021-12-7
编辑:Jan 2021-12-7
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 个评论
Emilio Pulli
Emilio Pulli 2021-12-7
ok thank you man but the main problem of inserting the text lines remain....
Emilio Pulli
Emilio Pulli 2021-12-7
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');

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Characters and Strings 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by