How to resolve error using save and output file copy titles?

3 vues (au cours des 30 derniers jours)
Lauren
Lauren le 13 Avr 2019
Commenté : Lauren le 13 Avr 2019
Hi, I'm trying to perform the following code but I keep getting an error using save. The code is supposed to load the filename and data for .txt files in a specified folder and shuffle the data from each .txt file using a SmallShuffle function to create the variable SS_data. It's then supposed to save multiple output files (18 copies plus the original filename copy) where each file contains one single column of shuffled data. The output files are supposed to be saved as the original filename plus the copy number...(ie. if the original file was called myfile.txt the output files should be myfile1.txt, myfile2.txt,...., myfile18.txt). Right now the non-command format works, but it only gives a single output file titled "outputfile". I have also tried using the command format: save (outputfile ,'SS_data','-ascii'); but it gives me an error "must be a string scalar or character vector". How could I resolve the output title problem and errors associated with save?
directory_name = uigetdir(pwd,'Select data directory');
directory_name = ([directory_name '/']);
files = dir([directory_name,'*txt']);
if isempty(files)
msgbox('No raw files in this directory')
end
FileName=[];
for i=1:length(files)
for j=1:18
filename=files(i).name;
data = load(filename,'-ascii');
filename=filename(1:end-4);
FileName=[FileName; cellstr(filename)];
outputfile = strcat(FileName,num2str(j),'.txt');
A=1;
SS_data=SmallShuffle(data,A);
save outputfile SS_data -ascii;
end
end

Réponse acceptée

Geoff Hayes
Geoff Hayes le 13 Avr 2019
Lauren - it looks like your FileName is a cell array instead of a string...this may be the source of your error. It's not clear to me why you are doing
FileName=[FileName; cellstr(filename)];
which is creating the cell array. Instead, consider something like
for i=1:length(files)
for j=1:18
filename=files(i).name;
data = load(filename,'-ascii');
outputfile= fullfile(directory_name, sprintf('%s%d.txt',filename(1:end-4), j));
A=1;
SS_data=SmallShuffle(data,A);
save(outputfile, 'SS_data', '-ascii');
end
end
Note how we use fullfile to create the full path to the file that is being saved. We use sprintf to create the filename that has the iteration number appended to it.
  1 commentaire
Lauren
Lauren le 13 Avr 2019
Thank you! That fixed the problem. It has been a while since I last worked with matlab, so that really saved me some frustration.
I am tasked with fixing/updating an existing code, so I am sure I will have similar questions eventually.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Environment and Settings dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by