dangerChihuahua007
dangerChihuahua007

Reputation: 20895

Why are these two implementations of max in matlab different?

I want to get the max of each item in an array compared to 5. What differs between these 2 snippets?

values = max(values, 5);

and

values(values < 5) = 5;

Is there a difference?

Upvotes: 2

Views: 64

Answers (3)

Mohsen Nosratinia
Mohsen Nosratinia

Reputation: 9864

There is difference if your matrix has NaN values:

>> values = [1 2 NaN -Inf Inf]
values =
     1     2   NaN  -Inf   Inf

>> max(values, 5)
ans =
     5     5     5     5   Inf

>> values(values < 5) = 5
values =
     5     5   NaN     5   Inf

As you see max(NaN, 5) == 5 but since NaN<5 is false the element containing NaN value won't be set to 5. If you want it to behave exactly like max you can try this:

>> values(~(values >= 5)) = 5
values =
     5     5     5     5   Inf

Upvotes: 2

Buck Thorn
Buck Thorn

Reputation: 5073

In this implementation both will give the same result.

In the general case max(A,B), the output contains the maximum of A or B at each element. The general equivalent would then be A(A<B) = B(A<B);

Upvotes: 1

P0W
P0W

Reputation: 47804

AFAIK there's no difference

But with second you can't preserve your old matrix, however with first one you can if you change the output variable name.

Upvotes: 1

Related Questions