Mahm00d
Mahm00d

Reputation: 3921

Matlab: What does the second argument in max(A,[],dim) mean?

I was just using max function on a specific column of a matrix and the syntax got me wondering:

What does this empty matrix passed as the second argument mean?

max(A,[],dim)

I know it's probably for separating it from max(A,i) which does the comparison. But, why an empty matrix?

Does it have a certain meaning? Is this kind of argument used in other functions like this?

Upvotes: 7

Views: 1338

Answers (4)

user1596274
user1596274

Reputation: 317

This has already been answered well, but, for completeness, let's imagine what it would look like if they didn't do this. To compare two values it would become:

max([A B])

We have extra, unnecessary square brackets, but it's like doing xlim([0 1]), so not a problem. But watch what happens if A is a vector and B is a scalar you want to compare against:

max([A; repmat(B, 1, numel(A))])

We already have something horrible in comparison to max(A, B), and you can imagine what happens with matrices and higher dimensions. And you also have to decide whether you need a comma or semicolon after "A".

Upvotes: 2

learnvst
learnvst

Reputation: 16195

The max function performs comparison of value pairs by default. Entering max(1,2) will obviously output 2. As another example, using max(x,0) is a neat way of performing half-wave rectification of x, comparing each value of x to the single value of 0. To compare the elements of a single matrix with the values contained within that matrix, the second argument can be specified as an empty matrix []. This acts as a flag to the function to compare values within the one matrix.

You'll see an empty value [] being used in many Matlab functions throughout the documentation. This often indicates a default value is to be used, or changes the mode of operation of the function.

Upvotes: 2

Dan
Dan

Reputation: 45752

It's allows you to compare two equal sized matrices to find the elementwise max. See the docs. Using [] as an input is just a way to skip ahead to a later input.

Upvotes: 2

Mikhail
Mikhail

Reputation: 21769

Actually, your guess is right. Since Matlab is not a strongly typed language and there is no classic function overloading technique, a function must guess of a meaning of an argument by the context. Mathworks wanted to merge both finding maximum within a single matrix and along of two arrays in a single function.

Thus they need to separate these cases somehow. And they use an empty matrix [] as a placeholder. Otherwise, they won't be able to separate cases max(A, dim) and max(A, B). They could have used any special variable for this purpose, but [] is the fundamental construction.

Upvotes: 11

Related Questions