How to save to a specific filename in a for loop

조회 수: 17 (최근 30일)
Jason
Jason 2014년 7월 25일
댓글: Image Analyst 2014년 7월 25일
So I have been having this issue for a while and I really would like to figure it out. I have a lot of data at 15 minute intervals and I want it over and hour. I have no issue doing this. The function that I call creates the correct OUTPUT. My issue is that I am not able to save the OUTPUT to a filename that takes the form ['data_1hr_2013',num2str(k)]. I need to figure out a way to save OUTPUT with the filename I create. Any help would be grealy appreciated. I could have sworn I used to do this all the time in previous versions of MATLAB. I am using 2014a now.
for k = 7:12
matFileName = sprintf('data_15min_2013%d.mat', k);
if exist(matFileName, 'file')
matData = load(matFileName);
else
fprintf('File %s does not exist.\n', matFileName);
end
OUTPUT = Conv15min2hr(eval(['matData.data_15min_2013',num2str(k)]));
save(['data_1hr_2013',num2str(k)],OUTPUT);
end
  댓글 수: 2
Star Strider
Star Strider 2014년 7월 25일
Do you get an error, or is the problem that when you look in the appropriate directory (or search) you can’t find the file?
Jason
Jason 2014년 7월 25일
I did get an error and I have now fixed this issue. So one more question. When I load data_1hr_2013.mat into the workspace it is labeled OUTPUT. Is there way to just call it data_1hr_20137 instead of OUTPUT?

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

채택된 답변

Image Analyst
Image Analyst 2014년 7월 25일
What on earth is that eval statement supposed to do???
Plus, OUTPUT should be in single quotes when you send it into the save function.
baseMatFileName= sprintf('data_1hr_2013%d.mat', k);
fullMatFileName = fullfile(folder, baseMatFileName); % folder = pwd or wherever...
save(fullMatFileName, 'OUTPUT');
  댓글 수: 2
Jason
Jason 2014년 7월 25일
I had to use the eval to pull the correct file into the function. Is there a better way for me to do this?
Image Analyst
Image Analyst 2014년 7월 25일
I'm sure there is, but I don't know what you want to do. The eval() is doing essentially like what would happen if you typed the name of that file onto the command line. What does that do? Does it return the structure that is stored in your .mat file? What kind of input is the function Conv15min2hr() expecting?

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

추가 답변 (1개)

Robert Cumming
Robert Cumming 2014년 7월 25일
BTW: eval is rarely the best choice...
I think you want:
% create your fieldname (sprintf is faster than str2num and joining using []
varName = sprintf ( 'matData.data_15min_2013%i', k );
% store your data in a struct using the above name:
matData.(varName) = OUTPUT;
% save the to file
save ( fullMatFileName, 'matData' );
% remove the field to avoid it being added to in the next loop.
matData = rmfield ( matData, varName );

카테고리

Help CenterFile Exchange에서 Data Type Conversion에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by