" It seems random, but that doesn't make sense."
It is not random, and it makes perfect sense.
According to the min documentation "If A is a vector, then min(A) returns the minimum of A", so for your examples we would expect the following output values:
- min([8,3,6,4]) -> 3
- min([7,3,5,2]) -> 2
- min([2,3,6,1]) -> 1
You then use those values as indices, which is a completely valid operation but those values are totally unrelated to the position of where the minimum values happen to be located in the original vector. So your examples are doing this:
- index 3 -> replace 3rd element
- index 2 -> replace 2nd element
- index 1 -> replace 1st element
Does the minimum value of 3 tell us anything about its location? No, it does not. But you used it as an index to change the 3rd element's value to Inf: if you tell MATLAB to change the 3rd element's value, then that is what it does. It makes absolutely no difference where that 3 comes from.
If you want to replace the elements with that minimum value, then you will need the indices of those values, e.g.:
>> x = [8,3,6,4];
>> x(min(x)==x) = Inf
x =
8 Inf 6 4
where min(x)==x generates a logical index of all elements of x which are equal to min(x).
Another option is to obtain the second output of min, which also gives the index of the first minimum value:
>> x = [8,3,6,4];
>> [~,y] = min(x);
>> x(y) = Inf
x =
8 Inf 6 4