Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optimal way to find max value and indices for all indices in cell of matrices

Tags:

matrix

matlab

I have 100 images each of size 512 by 512 stored in a cell array.

I want to find the max value and indices for each pixel location by searching all the images.

Here is the sample representation: enter image description here

My code:

imgs = cell(1,5);
imgs{1} = [2,3,2;3,2,2;3,1,1];
imgs{2} = [2,3,1;4,2,3;2,2,1];
imgs{3} = [3,2,1;5,3,5;3,2,3];
imgs{4} = [4,4,2;5,3,4;4,2,2];
imgs{5} = [4,5,2;4,2,5;3,3,1];

[nrows, ncols] = size(imgs{1});
maxVal_Mat = zeros(nrows,ncols);
maxIdx_Mat = zeros(nrows,ncols);
for nrow = 1:nrows
    for ncol = 1:ncols
        [maxVal_Mat(nrow, ncol), maxIdx_Mat(nrow, ncol)] = max(cellfun(@(x) x(nrow, ncol) , imgs));
    end
end

maxVal_Mat =

     4     5     2
     5     3     5
     4     3     3

maxIdx_Mat =

     4     5     1
     3     3     3
     4     5     3

Any ideas on how to optimize this code to save execution time and memory.

Note: This is a sample demonstration of the problem, the original cell and matrices are quite large.

Thanks,

Gopi

like image 530
Gopi Avatar asked Jun 12 '18 18:06

Gopi


1 Answers

Since all of your images are the same size it makes more sense to store them in a 3D matrix than a cell array, which also greatly simplifies performing operations like this on them. You can convert imgs from a cell array to a 3D matrix and find the maxima and indices like so:

imgs = cat(3, imgs{:});  % Concatenate into a 3D matrix
[maxValue, index] = max(imgs, [], 3)  % Find max across third dimension

maxValue =

     4     5     2
     5     3     5
     4     3     3

index =

     4     5     1
     3     3     3
     4     5     3

There is some discussion of using cell arrays versus multidimensional arrays in this post. In general, a multidimensional array will give you better performance for many operations, but requires contiguous memory space for storage (which can cause you to hit memory limits quicker for increasing array size). Cell arrays don't require contiguous memory space and can therefore be more memory-efficient, but complicate certain operations.

like image 177
gnovice Avatar answered Sep 30 '22 05:09

gnovice