필터 지우기
필터 지우기

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

조회 수: 3 (최근 30일)
Emilio Pulli
Emilio Pulli 2021년 12월 7일
댓글: Emilio Pulli 2021년 12월 7일
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.
Emilio Pulli
Emilio Pulli 2021년 12월 7일
fprintf write the data also in the matrix?

댓글을 달려면 로그인하십시오.

답변 (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