本文介绍了使用循环将多个值放入单元格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有31个主题(S1,S2,S3,S4等).每个主题都有3张图像,contrast1.img,contrast2.img和contrast3.img.我想使用循环将所有对象的对比度的所有路径都输入到称为P的nx1单元格中.P应该是这样的:

I have 31 subjects (S1, S2, S3, S4, etc.). Each subject has 3 images, contrast1.img, contrast2.img, and contrast3.img. I would like to use a loop to get all paths to the contrasts from all the subjects into a nx1 cell called P. P should be something like this:

Data/S1/contrast2.img

Data/S1/contrast2.img

Data/S1/contrast3.img

Data/S1/contrast3.img

Data/S2/contrast1.img

Data/S2/contrast1.img

Data/S2/contrast2.img

Data/S2/contrast2.img

Data/S2/contrast3.img ...

Data/S2/contrast3.img ...

Data/S31/contast3.img

Data/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个对比图像.以前的主题将被覆盖.这表明循环是错误的,但是我不确定如何解决.有人可以帮忙吗?

This, however, only give me P with the 3 contrast images of the last subject. Previous subjects get overwritten. This indicates that the loop is wrong but I'm not sure how to fix it. Could anyone help?

推荐答案

无需循环.使用 ndgrid 生成数字组合, num2str ,左对齐以转换为字符串,并且 strcat 进行连接,但不留空格:

No loop needed. Use ndgrid to generate the combinations of numbers, num2str with left alignment to convert to strings, and strcat to concatenate without trailing spaces:

M = 31;
N = 3;

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

这篇关于使用循环将多个值放入单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 15:35