How to read all the .txt files in a folder and convert them to matrixes?
조회 수: 3 (최근 30일)
이전 댓글 표시
I have a bunch of txt files in a folder (version 1,1.txt; version 1,2.txt; etc.). A sample file is attached. I need to convert the data into a matrix. I came up with the follwoing script. I appreciate your help to get it fixed.
% convert P-E scripts to E-P
clc, clear, close all;
Root='C:\Users\ski\CloudStation\Zahra\dissertation\stimuli and documents\methodStimuli\stimuli\english experiment/';
Drop='C:\Users\ski\CloudStation\Zahra\dissertation\stimuli and documents\methodStimuli\stimuli\farsi experiment/';
% Read
F = dir('*.txt');
for ii = 1:length(F)
fid = fopen(F(ii).name);
A=readtable(fid); %read the .dat file but dat data is converted to a table
B= table2array(fid); %dat table data is converted to an array. but the resluts are string and cells.
Bmtx = str2double(B); %convert the string , or cell?, to ordinary data matrix.
data=Bmtx;
end
% write the file
fid = fopen((fid),'wt'); %creating a txt type file.
for h = 1:size(data,1)
fprintf(fid,'%g\t',data(h,:));
fprintf(fid,'\n');
end
fclose(fid)
댓글 수: 0
답변 (1개)
Harsh
2018년 7월 20일
Due to the unique structure of this file, for more granular control on importing your data, you can use 'readtable' with d'etectImportOptions' for your data as follows:
>> opts = detectImportOptions('version 1, 2.txt');
>> opts.Delimiter = '\t';
>> opts.ExtraColumnsRule = 'ignore';
>> opts.VariableNames = {'label', 'mode', 'dur', 'win', 'iti', 'rdB','ldB', 'resp' 'type', 'filename'};
>> opts.VariableTypes = {'double', 'char', 'double', 'double', 'double','double', 'double', 'double', 'double', 'char'};
>> opts.SelectedVariableNames = {'label', 'dur', 'win', 'iti', 'rdB', 'ldB', 'resp', 'type'};
>> opts.DataLines = 5;
>> ans = table2array(readtable('version 1, 2.txt',opts));
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Data Type Conversion에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!