Craig
Craig

Reputation: 43

Matlab saving a .mat file with a variable name

I am creating a matlab application that is analyzing data on a daily basis. The data is read in from an csv file using xlsread()

[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

++++++++++++++ Sorry about not providing the full information. The error I get when I do the above is: Error using save Argument must contain a string.

And Xiangru and Wolfie, the save(fnSave, 'fnOpen') works as you suggested it would. Now I have a dallasTX.mat file, and the variable name inside is fnOpen. I can work with this now.

Thanks for the quick response.

Upvotes: 0

Views: 2249

Answers (2)

Wolfie
Wolfie

Reputation: 30047

From the documentation, when using the command

save(filename, variables)

variables should be as described:

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.

This means you should use

save(fnSave, 'fnOpen'); 

Since you want to also use a file name stored in a variable, command syntax isn't ideal as you'd have to use eval. In this case the alternative option would be

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

If you had a fixed file name (for future reference), this would be simpler

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

Upvotes: 0

Xiangrui Li
Xiangrui Li

Reputation: 2426

It would be helpful if you provide the error message when it doesn't work.

For this case, I think the problem is the syntax for save. You will need to do:

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

Also, you may use weather{i} instead of char(weather(i)).

Upvotes: 1

Related Questions