"Error using save Must be a string scalar or character vector." - but it is a string!

223 ビュー (過去 30 日間)
EQ
EQ 2019 年 4 月 7 日
コメント済み: Walter Roberson 2021 年 8 月 4 日
I'm getting the error when I run the following line:
save(['data/test',num2str(n),'.mat'],U,U_old,dt);
where n is my loop index. This is bizarre. For the record, when I stop at the breakpoint, typing this at the command line works:
save data/test1.mat U U_old dt
But I need to be able to change the filename within the loop, hence why I'm doing it the first way. When I type this at the command line:
['data/test',num2str(n),'.mat']
I get the expected 'data/test1.mat' result. The variable U is an 889x4 matrix, U_old is the same size, and dt is a single float. Even typing
save('data/test1.mat',U,U_old,dt);
at the command line when I stop gives me this error. What gives?

採用された回答

A. Sawas
A. Sawas 2019 年 4 月 7 日
編集済み: A. Sawas 2019 年 4 月 7 日
You need to enclose the variable names with qoutations like this:
save(['data/test',num2str(n),'.mat'],'U','U_old','dt');
  3 件のコメント
Jeet Shetty
Jeet Shetty 2021 年 8 月 4 日
what is n in your particular code, i have gotten the same error
Walter Roberson
Walter Roberson 2021 年 8 月 4 日
At the time the user got the error, n was 1.

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

その他の回答 (1 件)

Walter Roberson
Walter Roberson 2019 年 4 月 7 日
save( sprintf('data/test%d.mat', n), 'U', 'U_old', 'dt');
The quotes around the U and so on are the important part for your problem; the sprintf is just a cleaner way of creating the file name.
  2 件のコメント
Shuting Li
Shuting Li 2021 年 2 月 3 日
And where can I add filepath? I want to save file in other filepath? Thank you very much
Walter Roberson
Walter Roberson 2021 年 2 月 3 日
filename = fullfile(filepath, sprintf('test%d.mat', n));
save(filename, 'U', 'U_old', 'dt');

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

カテゴリ

Help Center および File ExchangeMatrices and Arrays についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by