使用循环将多个值放入单元格中

时间:2014-04-25 21:57:59

标签: matlab loops cell

我有31个科目(S1,S2,S3,S4等)。每个主题有3个图像,contrast1.img,contrast2.img和contrast3.img。我想使用一个循环来获得所有主题的对比的所有路径到一个名为P.的nx1单元格.P应该是这样的:

  

数据/ S1 / contrast1.img

     

数据/ S1 / contrast2.img

     

数据/ S1 / contrast3.img

     

数据/ S2 / contrast1.img

     

数据/ S2 / contrast2.img

     

数据/ S2 / contrast3.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

然而,这仅给出了P与最后一个主题的3个对比图像。以前的科目被覆盖。这表明循环错误但我不确定如何解决它。有人可以帮忙吗?

3 个答案:

答案 0 :(得分:1)

不需要循环。使用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')

答案 1 :(得分:0)

问题在于您指定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

答案 2 :(得分:0)

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

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

如果要访问第5个主题的第3张图像,请使用P{5,3}