How to read all the .txt files in a folder and convert them to matrixes?

9 views (last 30 days)
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.
% write the file
fid = fopen((fid),'wt'); %creating a txt type file.
for h = 1:size(data,1)

Answers (1)

Harsh on 20 Jul 2018
This is a good post to: process a sequence of files
If you have files that do not fit in memory, you can use a tabulartextdatastore
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));


Find more on Characters and Strings in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!