Search code examples
matlabmatrixminimum

Finding the minimum of corresponding elements in four matrices


So I need to find the minimum value of corresponding elements in multiple matrices. I did find this page but I would like to extend my question a little further. My matrices has positive and negative values (and zeros) and I want to find the minimum values excluding zeros.

Example:

Z(:,:,1) = [-5 0 5
             0 0 0
             1 0 3];

Z(:,:,2) = [1 0 2
            0 0 0
            0 0 0];

Z(:,:,3) = [0 0 0
           -9 0 4
            0 0 0];

Z(:,:,4) = [0 0 0
           -2 0 0
            0 0 0];

Here's what I'm using as of now:

Zmin = min(Z,[],3);

But that gives me:

[-5 0 0
 -9 0 0
  0 0 0]

But I want my result to be:

[-5 0 2
 -9 0 4
  1 0 3]

Any ideas? When I use nonzeros, it messes up everything.


Solution

  • Here's a workaround:

    Replace all the 0s in Z by NaN, calculate the min, then switch back to 0:

    clear all
    clc
    close all
    
    Z(:,:,1) = [-5 0 5
        0 0 0
        1 0 3];
    
    Z(:,:,2) = [1 0 2
        0 0 0
        0 0 0];
    
    Z(:,:,3) = [0 0 0
        -9 0 4
        0 0 0];
    
    Z(:,:,4) = [0 0 0
        -2 0 0
        0 0 0];
    
    %// Assign NaN to 0 elements
    Z(Z ==0) = NaN;
    
    Zmin = min(Z,[],3);
    
    %// Switch back with 0
    Zmin(isnan(Zmin)) = 0;
    
    %// Same for Z;
    Z(isnan(Z)) =0;
    

    The output looks like this:

    Zmin
    Z
    
    Zmin =
    
        -5     0     2
        -9     0     4
         1     0     3
    
    
    Z(:,:,1) =
    
        -5     0     5
         0     0     0
         1     0     3
    
    
    Z(:,:,2) =
    
         1     0     2
         0     0     0
         0     0     0
    
    
    Z(:,:,3) =
    
         0     0     0
        -9     0     4
         0     0     0
    
    
    Z(:,:,4) =
    
         0     0     0
        -2     0     0
         0     0     0