How to save function workspace to specific directory within the function?

4 次查看(过去 30 天)
Hello, I am trying to save the workspace produced in a function to a certain directory. The main file calls the function:
sheet = [1 3 4 5 6 7];
name = ['BS7910' 'BS7910 CorrectR' 'Han' 'Han Plasticity' 'PLNR' 'Han PLNR'];
for k = 1:length(sheet)
[N_error(k,:), ov_error(k,:), results(k*3-2,:)] = Parametric_Analysis_FUNCTION(sheet(k),name(k));
end
And the function is the following:
function Parametric_Analysis_FUNCTION(sheet,name)
directory = sprintf('Results_%s',name); % Directory to save the outputs
number = 1;
saveName = ['C:\Users\Matteo Schiaretti\Desktop\',directory,'\Model_',num2str(number),'_',name,'.mat'];
save(saveName)
If I manually input all the lines in the command window the workspace is being save correctly, instead, if I run the main function, the following error pop out:
Error using save
Cannot create 'Model_1_B.mat' because 'C:\Users\Matteo Schiaretti\Desktop\Results_B' does not exist.
Error in Parametric_Analysis_FUNCTION (line 178)
save(saveName)
Error in BATCH_EXECUTES (line 12)
[N_error(k,:), ov_error(k,:), results(k*3-2,:)] = Parametric_Analysis_FUNCTION(sheet(k),name(k));
What is the problem? Why is the directory cut in the error? Do you have any solution?
EDITED
To be more precise, the error is citing 'C:\Users\Matteo Schiaretti\Desktop\Results_B' but the correct directory is existing and should be 'C:\Users\Matteo Schiaretti\Desktop\ Results_BS7910', as for the first string in the name vector.

回答(1 个)

Deepak Bhatia
Deepak Bhatia 2017-3-3
There are several things that need to be addressed above:
1. The variable "name" should be a cell array not a character array. The "[]" will concatenate all the strings present between the brackets. Hence, the first character is indexed when doing "name(k)".
2. Based on your explanation above, it seems that you want to create new directories programmatically. If that is the case, then consider using mkdir to make the directories with the path that you want. I recommend modifying the directory variable to be as follows:
>> fileName = ['Results_',name];
>> directory = ['C:\Users\Matteo Schiaretti\Desktop\',fileName,'\Model_',num2str(number),'_',name]
3. The function save accepts file names but it seems that you are passing a path name instead. I recommend doing the following:
>> saveName = [name, '.mat']
>> save(saveName)
4. Consider moving the MAT files to the correct destination by using movefile as follows:
>> movefile(saveName,directory)
5. There are no output arguments for the "Parametric_Analysis_FUNCTION" from the snippet above, so make sure you there are output arguments being returned by the function.

类别

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