필터 지우기
필터 지우기

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

조회 수: 2 (최근 30일)
Lauren
Lauren 2019년 4월 13일
댓글: Lauren 2019년 4월 13일
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

채택된 답변

Geoff Hayes
Geoff Hayes 2019년 4월 13일
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
Lauren
Lauren 2019년 4월 13일
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.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Environment and Settings에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by