Matlab 用变量名保存一个 .mat 文件

Matlab saving a .mat file with a variable name

我正在创建一个每天分析数据的 matlab 应用程序。 使用 xlsread()

从 csv 文件中读取数据
[num, weather, raw]=xlsread('weather.xlsx');
% weather.xlsx is a spreadsheet that holds a list of other files (csv) i 
% want to process
for i = 1:length(weather)
    fn = [char(weather(i)) '.csv'];

    % now read in the weather file, get data from the local weather files
    fnOpen = xlsread(fn);

    % now process the file to save out the .mat file with the location name
    % for example, one file is dallasTX, so I would like that file to be 
    % saved as dallasTx.mat
    % the next is denverCO, and so denverCO.mat, and so on.
    % but if I try...
    fnSave=[char(weather(i)) '.mat'] ;
    save(fnSave, fnOpen) % this doesn't work

    % I will be doing quite a bit of processing of the data in another 
    % application that will open each individual .mat file
end

++++++++++++++ 很抱歉没有提供完整的信息。 执行上述操作时出现的错误是: 使用保存时出错 参数必须包含一个字符串。

还有相如和 Wolfie,save(fnSave, 'fnOpen') 按照您的建议工作。现在我有一个dallasTX.mat文件,里面的变量名是fnOpen。我现在可以使用它了。

感谢您的快速回复。

如果您在它不起作用时提供错误消息,将会很有帮助。

对于这种情况,我认为问题出在 save 的语法上。您将需要做:

save(fnSave, 'fnOpen'); % note the quotes

此外,您可以使用 weather{i} 而不是 char(weather(i))。

来自documentation,当使用命令

save(filename, variables)

variables 应该如描述的那样:

Names of variables to save, specified as one or more character vectors or strings. When using the command form of save, you do not need to enclose the input in single or double quotes. variables can be in one of the following forms.

这意味着您应该使用

save(fnSave, 'fnOpen'); 

由于您还想使用存储在变量中的文件名,因此命令语法并不理想,因为您必须使用 eval。在这种情况下,替代选项是

eval(['save ', fnSave, ' fnOpen']);

如果你有一个固定的文件名(供将来参考),这会更简单

save C:/User/Docs/MyFile.mat fnOpen