0

An array having multiple infinite values as +inf and -inf. How to replace -inf by minimum value present in that array and +inf by maximum value of the same array. The array is an output of some calculation so it is unknown to us initially. However, just an example take an array as A=[inf, 1, 2, inf, 0, -4, -inf, -1, -inf]. Here min and max are clearly given as -4 and 2 and I can replace it easily using looping. How to do it for the resultant array of some calculation. I Will be thankful for your valuable suggestions.

1 Answers1

9

Matlab has a great capacity called logical indexing. It means that you can index your array with a Boolean array of the same length.

A=[inf, 1, 2, inf, 0, -4, -inf, -1, -inf]

%Replace the values where A==-inf with the minimum real number.
A(A==-inf) = min(A(isfinite(A)));
%Replace the values where A==+inf with the maximum real number.
A(A==inf)  = max(A(isfinite(A)));
obchardon
  • 10,614
  • 1
  • 17
  • 33
  • ... or even of _different_ length :-) (see [this answer](http://stackoverflow.com/questions/1710299/corner-cases-unexpected-and-unusual-matlab/2462898#2462898), edit 3) – Luis Mendo Jan 27 '17 at 13:07