How do I use chunks from strsplit in Matlab to save along with my data in a text file?

2 visualizzazioni (ultimi 30 giorni)
I have a list of over 600 files that I would like to extract the information from the file name and put it into the text file along with the information in the file itself.
Example:
name of file:
p01.male.cond.1.loud.txt
info in file:
0.015 120 50
0.12 121 52
0.23 119 53
0.4 122 59
I would like the file to look like this:
p01 male cond 1 loud 0.015 120 50
p01 male cond 1 loud 0.12 121 52
p01 male cond 1 loud 0.23 119 53
p01 male cond 1 loud 0.4 122 59
I used strsplit to extract the names from the file name but I do not know how to use the chunks from strsplit to put into a data file. PLEASE HELP!!! the code needs to be general enough to apply to the 600 files that I have that all have a similar name structure but different names and different file contents.

Risposte (2)

Guillaume
Guillaume il 4 Feb 2016
You would basically loop over your files, read the content, add the prefix (see tudor's answer and related comments) to each line, and rewrite (preferably to a different file to eliminate the risk of losing data). Something like:
%filenames: a cell array of file names (strings). Possibly obtained with dir
%folder: the full path of the folder containing the files (string).
for fileindex = 1:numel(filenames)
testconditions = strsplit(filename{fileindex}, '.');
prefix = strjoin(testconditions(1:end-1), '\t');
fin = fopen(fullfile(folder, filename{fileindex}), 'rt');
fout = fopen(fullfile(folder, ['modified -', filename{fileindex}]), 'wt');
tline = fgetl(fid);
while ischar(tline)
if ~isempty(tline)
fprintf(fout, '%s\t', prefix);
end
fprintf(fout, '%s\n', tline);
end
fclose(fin);
fclose(fout);
end

tudor dima
tudor dima il 4 Feb 2016
% try this
>> prefix = regexprep(filename,'\.','\t')
prefix = p01 male cond 1 loud txt
  2 Commenti
Walter Roberson
Walter Roberson il 4 Feb 2016
Easier:
filename(filename == '.') = sprintf('\t');
This works because tab is just a single character, char(9)
Guillaume
Guillaume il 4 Feb 2016
Modificato: Guillaume il 4 Feb 2016
Except that both these solution keep the original extension that is not wanted.
testconditions = strsplit(filename, '.');
prefix = strjoin(testconditions(1:end-1), '\t')
would make more sense

Accedi per commentare.

Categorie

Scopri di più su Migrate GUIDE Apps in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by