how to save a string as a filename?

56 ビュー (過去 30 日間)
Subrat kumar sahoo
Subrat kumar sahoo 2012 年 7 月 5 日
コメント済み: Amir Pasha Zamani 2020 年 9 月 19 日
Hi, How to save a file "with the characters of a string" as the file name? For example, I have a piece of code, which generates a sting output "case study_# " and the number (#) changes each time I feed in different inputs. I want the name of the output file to be saved, based on the string output. Thanks, Subrat

採用された回答

Thomas
Thomas 2012 年 7 月 5 日
編集済み: Stephen23 2017 年 2 月 17 日
Maybe something like this
for number=1:10
file_name = sprintf('case study_#%d.txt',number);
save(file_name,...);
end
  1 件のコメント
Amir Pasha Zamani
Amir Pasha Zamani 2020 年 9 月 19 日
It doesn´t work for me
My code is something like this:
for Animal=1:N
Data = {rand(2,2) ; rand(3,3)};
file_name = ['Animal_' , num2str(Animal)];
save (file_name , Data)
end
But when I run it, I get the error:
Error using save
Argument must contain a character vector.
:(
Can anyone help please?

サインインしてコメントする。

その他の回答 (2 件)

Jan
Jan 2012 年 7 月 7 日
This is an evergreen question, See FAQ: How to process files in a loop.
It is strongly recommended to read the other frequently asked questions also. It is worth to profit from the problems others had already.

Albert Yam
Albert Yam 2012 年 7 月 5 日
for i=1:2;
save(['test_' num2str(i)]);
end
  1 件のコメント
Albert Yam
Albert Yam 2012 年 7 月 6 日
I'm quoting your response, in case it can help someone else.
For example, if the name of the sting is 'a' and it generates the output as "case_study_test_simulation"
a = case_study_test_simulation;
then I expect the saved file to have the file name as "case_study_test_simulation.mat." Instead, I end up getting the file name as "a.mat."
From what I understand (I'm writing it out as 'I' would read it), you have a variable 'a' that contains a string 'case_study_test_simulation' (as opposed to string string a). so
a = 'case_study_test_simulation'; %note the quotes
save(a) %this will produce what you are asking for
%'case_study_test_simulation.mat
save('a') %will produce a.mat
This is because Matlab reads string 'a', not variable 'a' (that contains string 'case_study_test_simulation'

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeWorkspace Variables and MAT-Files についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by