如果不存在,matlab保存创建目录

时间:2017-03-22 06:05:34

标签: arrays string matlab char save

我正在尝试编写一个MATLAB函数,该函数扩展“save”命令以创建指定的路径(如果它尚不存在)。我已成功使用单个变量,但没有多个变量。使用多个变量,我收到以下错误消息:

31                  variables_to_save(i) = variable_name;
Conversion to cell from char is not possible.

Error in saveMatVars (line 31)
            variables_to_save(i) = variable_name;

这是我的功能:

function saveMatVars( file_path, varargin )
%saveMatVars saves variables in varargin to file specified in file_path, creating the file path if it doesn't exist
%   varargin is the variables to save

% get path and filename from file_path
[parent_folder, ~] = fileparts(file_path);

% if parent_folder doesn't exist, create it
if ~exist(parent_folder, 'dir')
    mkdir(parent_folder);
end

% get names of variables to save
num_vars = length(varargin);
switch num_vars
    case 0
        return
    case 1
        variable_name = inputname(2);
        variable_name = matlab.lang.makeValidName(variable_name);
        variable_val = varargin{1};           
        feval(@()assignin('caller', variable_name, variable_val)); % create
 a dummy function so I can access the current function's workspace
        variables_to_save = variable_name;
    otherwise % note - this part does not work
        variables_to_save = cell(1,1);
        for i = 1:num_vars
            variable_name = inputname(i+1);
            variable_name = matlab.lang.makeValidName(variable_name);
            variable_val = varargin{i};
            feval(@()assignin('caller', variable_name, variable_val)); % create a dummy function so I can access the current function's workspace
            variables_to_save(i) = variable_name;
        end
        variables_to_save = string(variables_to_save);
end
% save variables_to_save in file_path
save(file_path, variables_to_save);
return
end

关于“保存”的文档说明了要保存的变量:

save(filename,variables) saves only the variables or fields of a structure array specified by variables.

我已尝试过将char数组转换为字符串和单元格数组的各种函数,但无效。

0 个答案:

没有答案