Using loops to get multiple values into a cell

帅比萌擦擦* 提交于 2019-12-11 08:52:21

问题


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/contrast1.img

Data/S1/contrast2.img

Data/S1/contrast3.img

Data/S2/contrast1.img

Data/S2/contrast2.img

Data/S2/contrast3.img ...

Data/S31/contast3.img

This is what I've tried:

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

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?


回答1:


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')



回答2:


I would use a cell matrix, which directly represents the subject index and the contrast index.

To preallocate use P=cell(length(A),length(C)) and to fill it use P{i,j}=...

When you want to access the 3rd image of the 5th subject, use P{5,3}




回答3:


The problem is where you assign P{j}.

Since j only loops 1:3 and doesn't care about i, you are just rewriting all three values for P{j}. I think you want to concatenate the new values to the cell array instead

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

or you could assign each value directly such as

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


来源:https://stackoverflow.com/questions/23303730/using-loops-to-get-multiple-values-into-a-cell

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!