SKM
SKM

Reputation: 989

Issue in bounding values of matrix

Problem : I need to clamp each of the elements of P matrix in the range [-1,1]. I have used the code MinMaxCheck provided but this code works only for vectors. So, I have modified it to work for matrix. The modified function code MinMaxCheckMatrix does change only the first column but the second column elements are not checked nor clamped. I am unable to understand why the entire P matrix is not getting affected. Please help in rectifying.

 SomeVector =     [20 0
                     -20 1
                      5 0.9
                      1.1 0.2
                      10  20];

 for rows =1:5
  P(rows,:) = SomeVector;
  min_range(rows,:)=-1;
  max_range(rows,:)=1;
end
 P = MinMaxCheckMatrix(min_range, max_range, P);

**Function**
function [ A2comp ] = MinMaxCheckMatrix( minimum, maximum, A2comp )
[row col] = size(minimum);

for i=1:row
    for j=1:col
        if(maximum(i,j)<A2comp(i,j)||minimum(i,j)>A2comp(i,j))
            if(maximum(i,j)<A2comp(i,j))
                A2comp(i,j)=maximum(i,j);
            else A2comp(i,j)=minimum(i,j);
            end
        end
   end
end


This is the result that I got:

P =

    1.0000         0
   -1.0000    1.0000
    1.0000    0.9000
    1.0000    0.2000
    1.0000   20.0000

Upvotes: 2

Views: 396

Answers (3)

Royi
Royi

Reputation: 4963

I usually like writing something like this:

function [ mO ] = ClampArray( mO, minVal, maxVal )

mO = max(min(mO, maxVal), minVal);


end

Now all you need is P = ClampArray(P, -1, 1);.

Upvotes: 1

Notlikethat
Notlikethat

Reputation: 20944

Unless I'm missing something, that seems like a very overcomplicated way to do this:

P(P < -1) = -1;
P(P > 1) = 1;

or, fancier:

function mat = clamp(mat, minval, maxval)
mat(mat < minval) = minval;
mat(mat > maxval) = maxval;

Upvotes: 2

Ben Voigt
Ben Voigt

Reputation: 283694

It's because size(minimum) is not the same as size(A2comp).

Looking at

P(rows,:) = SomeVector;
min_range(rows,:)=-1;
max_range(rows,:)=1;

The number of columns is determined by the right-hand side, and so min_range and max_range as created with only one column.

You could just vectorize this:

function [ A2comp ] = MinMaxCheckMatrix( minimum, maximum, A2comp )
    A2comp = bsxfun(@max, A2comp, minimum);
    A2comp = bsxfun(@min, A2comp, maximum);
end

Upvotes: 1

Related Questions