Search code examples
arraysmatlabfor-loopindexingstoring-data

Store arrays in index in a nested for loop in matlab


I have 50 images, stored as arrays in a 1x50 cell index called AllImages. Basically I want to make a new index with arrays that contain elements in the same position of the 50 arrays.

I want to see how each pixel in the same spot of the 50 images changes in the 50 images.

Theoretically, I would get an index of arrays with 50 elements each, because I want the first element of each of the 50 arrays in its own array, the second element of each of the 50 arrays in its own array, so on and so forth.

So far, here is my code:

for m = 1:5000 % number of pixels per image
    for n = 1:50 % for the 50 images, all the same size
        pixels(n) = allImages{n}(m)
    end
    allpixels{m} = pixels
end

I end up getting a 1x50 cell index for allpixels, even though I want 5000. I'm not sure what I did wrong.

Is there an easier way to do this or fix the code? Thanks so much!


Solution

  • are the images of the same size? in that case first change them to a matrix using cell2mat

    [i,j] = size(allImages{1})
    n = numel(allImages)
    allImages = cell2mat(allImages);
    allImages = reshape(allImages,[i,j,n]);
    

    because now you can just select your pixel. for example:

    pixel = squeeze(allImages(1,1,:))
    

    To get them all in a new cell you could permute and reshape your matrix

    allImages = permute(allImages ,[3 1 2]);
    allImages = reshape(allImages ,[n,i*j]);
    pixels = mat2cell(allImages,n,ones([1,i*j]));
    

    But for most mathematical operations it is easier to just keep them as one matrix.

    As two rules of thumb in matlab you want to use matrices as much as possible, and avoid for-loops.