使用循环将多个值获取到一个单元格中



我有31个受试者(S1、S2、S3、S4等)。每个受试者都有3个图像,contrast1.img、contrast2.img和contrast3.img。我想使用一个循环将所有受试者的对比度的所有路径获取到一个名为p.p的nx1细胞中。p应该是这样的:

数据/S1/contrast1.img

数据/S1/contrast2.img

数据/S1/contrast3.img

数据/S2/contrast1.img

数据/S2/contrast2.img

数据/S2/contrast.img…

数据/S31/contast3.img

这就是我尝试过的:

A={'S1','S2','S3',...,'S31'}; % all the subjects 
C={'contrast1.img','contrast2.img','contrast3.img'}; % contrast images needed for each subject
P=cell(31*3,1)
for i=1:length(A)
    for j=1:length(C)
     P{j}=spm_select('FPList', fullfile(data_path, Q{i}) sprintf('%s',cell2mat(C(j)))); % this is to select the three contrast images for each subject. It works in my script. It might not be 100% correct here since I had to simplify for this example.
    end
end

然而,这只给了我最后一个主题的3个对比度图像的p。以前的主题被覆盖。这表明循环是错误的,但我不知道如何修复。有人能帮忙吗?

不需要循环。使用ndgrid生成数字组合,使用左对齐的num2str转换为字符串,使用strcat连接而不带尾随空格:

M = 31;
N = 3;
[jj ii] = ndgrid(1:N, 1:M);
P = strcat('Data/S',num2str(ii(:),'%-i'),'/contrast',num2str(jj(:),'%-i'),'.img')

我会使用一个单元格矩阵,它直接表示主题索引和对比度索引。

预分配使用P=cell(length(A),length(C)),填充使用P{i,j}=...

当您想访问第5个受试者的第3张图像时,请使用P{5,3}

问题是在哪里分配p{j}。

由于j只循环1:3,而不关心i,因此您只需重写p{j}的所有三个值。我认为您希望将新值连接到单元格数组,而不是

for i=1:length(A)
    for j=1:length(C)
        P ={P; spm_select('FPList', fullfile(data_path, Q{i}) sprintf('%s',cell2mat(C(j))));}
    end
end

或者你可以直接分配每个值,比如

for i=1:length(A)
    for j=1:length(C)
        P{3*(i-1)+j} =spm_select('FPList', fullfile(data_path, Q{i}) sprintf('%s',cell2mat(C(j))));
    end
end

相关内容

最新更新