Darrik
Darrik

Reputation: 55

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.

Upvotes: 0

Views: 54

Answers (2)

Benoit_11
Benoit_11

Reputation: 13945

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

Upvotes: 1

Cape Code
Cape Code

Reputation: 3574

One option is to set all zero elements to NaN that way:

Z(Z==0)=NaN;

And then use nanmean

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

Upvotes: 0

Related Questions