How to search and extract specific string and data and write into new variable from file ?

조회 수: 14 (최근 30일)
I have data containes lot of different values like this
BULK VARIABLES NW= 0.197E+10 QW= 0.302E-03 QWA= 0.931E-07
QSO2= 0.000E+00 QO3= 0.000E+00 QH2O2= 0.000E+00 QCO2= 0.000E+00 QNH3= 0.000E+00 QSO4 = 0.000E+00 QHMO3= 0.000E+00 pH= 0.594E+01 CONDUCT= 0.239E-01
And I would like to search pH= ****** at every line and extract from the file and write into a new variable (nx1).
you can find sample file in attached file.

채택된 답변

Jeevan Kumar Bodaballa
Jeevan Kumar Bodaballa 2020년 11월 3일
I found soultion for this
I am attching sample file also for better understanding
clear
fid = fopen('f20_CHEMISTRY.TXT','r');
data = textscan(fid,'%s');
fclose(fid);
Str = string(data{:});
% this loop for pH values
%check the numbers(33 to 1484 in my case)
% In str array from where you want to make reshape
% below loop will extract the value and write new array
y = 1;
for j = 33:1484:length(Str)
f20_pH(y) = Str(j,:);
y = y+1;
end
f20_pH = str2double(f20_pH);
save('f20_pH_con.mat','f20_pH')

추가 답변 (1개)

Anmol Dhiman
Anmol Dhiman 2020년 9월 10일
Hi Jeevan,
You can follow the below approach
fid = fopen('pH.txt'); % Open the file
line_ex = fgetl(fid); % read a line
newStr = split(line_ex); % split the line based on delimeter space.IT gives a cell array
indexOfPH = find(contains(newStr, 'pH=')); % search if any of the elements is mathing with 'pH='
newVariable = newStr{indexOfPH+1} ; % store the value in a variable
% To read next line
line_ex = fgetl(fid);
You need to write in a loop.
Regards,
Anmol Dmiman
  댓글 수: 1
Jeevan Kumar Bodaballa
Jeevan Kumar Bodaballa 2020년 9월 26일
편집: Jeevan Kumar Bodaballa 2020년 9월 26일
Sorry for late answer
I follow the script you wrote but I am getting error at 5th line
'Unable to perform assignment with 0 elements on the right-hand side.'
Also please suggest the loop as well.

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

카테고리

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