调用由变量和通配符定义的文件

时间:2016-10-25 14:59:29

标签: matlab

我试图遍历由变量定义的文件夹,并选择由通配符定义的单个文件(在matlab R2012a中)。示例文件为:/folder1/folder2/601/mprage/xyz.nii。在研究这个时,我试图通过dir和fullfile整合变量和通配符,但是得到一个horzcat(从char转换为struct是不可能的)错误。最终,该文件将由函数' callspmsegmentation'处理。我是matlab编程的新手......这是我的脚本:

clear all

studyDir = '/folder1/folder2';
anatDir = 'mprage';
subjects = {'601', '602', '603'};

for jSubj = 1:length(subjects)
niiname = dir(fullfile(studyDir, subjects{jSubj}, anatDir, '*.nii')); 
nii = [studyDir '/' subjects{jSubj} '/' anatDir '/' niiname];
callspmsegmentation(nii);
end

或者,我尝试的更直接:(也没有工作)

clear all

studyDir = '/folder1/folder2';
anatDir = 'mprage';
subjects = {'601', '602', '603'};

for jSubj = 1:length(subjects) 
nii = [studyDir '/' subjects{jSubj} '/' anatDir '/*.nii'];
callspmsegmentation(nii);
end

1 个答案:

答案 0 :(得分:1)

dir的输出是struct 而不是字符串,因此您必须访问name字段才能获取文件名

niiname = dir(fullfile(studyDir, subjects{jSubj}, anatDir, '*.nii')); 
nii = [studyDir '/' subjects{jSubj} '/' anatDir '/' niiname.name];

我也可能会重新编写它以使用fullfile,这样就不会对所有这些文件分隔符进行硬编码。这样的事情应该有效。

% Store the folder name
folder = fullfile(studyDir, subjects{jSubj}, anatDir);

% Get the file listing
file = dir(fullfile(folder, '*.nii'));

% Append the folder to the filename
nii = fullfile(folder, file.name);

% Process the file
callspmsegmentation(nii);