2016-08-17 122 views
0

所以我有一個非常簡單的問題,我試圖解決。我想在MATLAB中創建一個文件的備份。MATLAB複製文件錯誤:參數必須包含一個字符串

這裏是我的代碼(我開始從我的當前目錄這個腳本):

backup_dir=strcat(pwd,'/backups/'); 
cd('../../source_destination/'); 
source_dir=pwd; 
cd(backup_dir); 

source_files=strcat(source_dir,'/*.m'); 
source_file_list=dir(source_files); 
source_file_names={source_file_list.name}'; 

for i=1:numel(source_file_names) 
    source_file=strcat(source_dir,'/',source_file_names(i)); 
    backup_file=strcat(backup_dir,source_file_names(i)); 
    copyfile(source_file,backup_file); 
end 

運行這個給我的錯誤:

Error using copyfile 
Argument must contain a string. 

然而,當我真正審視source_filebackup_file ,兩個變量都會返回一個有效字符串(由' '包含),並且兩個字符串都指向有效文件:

>> source_file 

source_file = 

    '/Users/me/mydir/cool/source_destination/archive.m' 

>> backup_file 

backup_file = 

    '/Users/me/mydir/cool/world/scripts/backups/archive.m' 

此外,source_file_list的實際內容是有效的。

那麼,爲什麼我會得到這個錯誤?

回答

1

您需要取消引用與大括號中cell陣列的內容,否則strcat回報cell字符串數組:

for i=1:numel(source_file_names) 
    source_file=strcat(source_dir,'/',source_file_names{i}); 
    backup_file=strcat(backup_dir,source_file_names{i}); 
    copyfile(source_file,backup_file); 
end 
+1

謝謝!我猜想我錯誤地認爲'source_file_names(i)'會返回一個字符串,因爲當我實際顯示它時,它顯示爲用引號包圍,而'source_file_names {i}'沒有顯示在引號中。 – Alex

+0

@Alex確實。由於'cell'數組中固有的靈活性,它們需要一種特殊形式的引用來訪問實際內容與通用元素。這是一些習慣,但非常強大。 – TroyHaskin

+2

我知道問題是單元格數組,但不是使用'strcat',我更喜歡使用'fullfile'。恕我直言,更容易閱讀和理解。 'fullfile(source_dir,source_file_names {i});' –

相關問題