Add commas between number columns from text file
古いコメントを表示
Hello,
First time asking throught the forum.
I have a text file with some information that I want to extract as a matrix to work with later on.
The first file (ReactionsPortic5Combination4.txt) is the raw information out of another programm and the second one (5_4.txt) is the first one processed so only the rows with information remain. My problem is that the columns FZ (4th column) and MX (fifth column) are too near and when I try to extract the matrix I have a 5 column matrix with a NaN value column.
How could I add commas between the numbers for all files like this so this issue doesn't happen.
Thanks in advance.
function [Matrix] = ObtainTxtWithNumber(NameTxt,...
NumPortic,NumComb)
% NameTxt = "ReactionsPortic5Combination4.txt"; (in the case exposed)
% NumPortic = 5; (in the case exposed)
% NumComb = 4; (in the case exposed)
NumLines = linecount(NameTxt); % This linecount function is a copied and pasted function I found
% in this forum. Thanks for the answers to that post and for the one
% who asked in the post too.
% It counts the lines that are in the text file
tfile = GenerateFileName(NumPortic,NumComb);
fin = fopen(NameTxt,'r');
fout = fopen(tfile, 'w');
% I generate another txt file and write the lines I pick
% from the other txt
for i = 1:NumLines
inline = fgets(fin);
if i > 11.5 && i < NumLines - 2.5
fwrite(fout, inline);
% Write only the lines with information
end
end
fclose(fin);
fclose(fout);
fout = fopen(tfile,'r');
Matrix = readmatrix(tfile);% Option 1
fclose(out);
end
採用された回答
その他の回答 (1 件)
Given the fixed format nature of these files, the best thing to do is probably to just build a specific fixed-width import options object for them that is hand-built to match the specific format.
The following should work for all your files regardless the actual data format in the fields; using the %g format for such may be somewhat convenient to the human reader, but makes parsing a little more problematic unless and until one sees the actual format in enough incarnations to recognize what it is.
fn='https://www.mathworks.com/matlabcentral/answers/uploaded_files/1368144/ReactionsPortic5Combination5.txt';
opt=fixedWidthImportOptions('NumVariables',7, ...
'VariableWidths',[8,14,13,13,13,13,13], ...
'VariableTypes',repmat({'double'},1,7), ...
'VariableNamesLine',11, ...
'DataLines',12, ...
'PartialFieldRule','omitrow', ...
'MissingRule','omitrow');
tData=readtable(fn,opt);
[head(tData,4);tail(tData,4)]
カテゴリ
ヘルプ センター および File Exchange で Tables についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!