Save a matrix .mat in a specific folder with a variable name

조회 수: 71 (최근 30일)
Emilio Pulli
Emilio Pulli 2022년 1월 4일
편집: Yongjian Feng 2022년 1월 4일
I would like to save a matrix as a .mat file in a specific folder. The save function is located at the end of a for loop and, therefore, it is needed to be saved with a variable name changing each loop iteration. At the moment I am able to save the .mat file in a specific folder but I am not able to save it with the desired variable name. I am now using this function:
save('filepath','variablename')
where the variablename is the name of the .mat file that needs to be saved.
Thank you all!

채택된 답변

Yongjian Feng
Yongjian Feng 2022년 1월 4일
편집: Yongjian Feng 2022년 1월 4일
Try something this:
a = 100;
for i=1:3
file_name = ['filename' num2str(i)];
save(file_name, 'a');
end
  댓글 수: 2
Emilio Pulli
Emilio Pulli 2022년 1월 4일
Your method works but it does not include a way to save the variable in a desired folder
Yongjian Feng
Yongjian Feng 2022년 1월 4일
편집: Yongjian Feng 2022년 1월 4일
If you want to use the same folder but different file names:
a = 100;
folder_name = 'tmp';
if ~exist(folder_name, 'dir')
mkdir(folder_name);
end
for i=1:3
file_name = ['filename' num2str(i)];
filepath = fullfile(folder_name, file_name);
save(filepath, 'a');
end
Or if you want to use different folders:
a = 100;
for i=1:3
folder_name = ['folder' num2str(i)];
if ~exist(folder_name, 'dir')
mkdir(folder_name);
end
filepath = fullfile(folder_name, 'filename');
save(filepath, 'a');
end

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

추가 답변 (1개)

dpb
dpb 2022년 1월 4일
save(filepath,'variablename')
The functional form of save needs the file name to be the variable containing the (hopefully fully-qualified) desired filename, the variable name must be the literal string matching the variable to be saved.
  댓글 수: 1
Emilio Pulli
Emilio Pulli 2022년 1월 4일
편집: Emilio Pulli 2022년 1월 4일
I need a way to both save the variable in a specific folder with a desired name. If you point me a way of how correctly placing these infos into the brackets of the save function I could figure the problem out

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

카테고리

Help CenterFile Exchange에서 File Operations에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by