1

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?

bla
  • 25,846
  • 10
  • 70
  • 101
A.Rainer
  • 719
  • 5
  • 16

3 Answers3

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')
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
0

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
0

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}

Daniel
  • 36,610
  • 3
  • 36
  • 69
  • Thank you for your response! This almost works but P has to be a 93x1 cell and the images has to be in the same order as I mentioned in my original message (i.e. sorted by subjects then sorted by contrasts). – A.Rainer Apr 26 '14 at 00:01