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!