# LINDEX Examples

The function `LINDEX` converts the subscript index output from MATLAB's inbuilt MIN and MAX functions into linear indices. The linear indices are such that when used on the same array that was input to MIN/MAX they will create the same output array:

[C,I] = max(A); % OR min(A) OR max(A,[],dim) OR min(A,[],dim) J = lindex(size(A),I); isequal(C,A(J)) ans = 1

## Contents

## Concept Example

For this example output `I` are subscript indices for the first dimension:

```
A = [1,9,2,8;3,7,4,5]
[C,I] = max(A)
J = lindex(size(A),I)
A(J) % the same as C!
```

A = 1 9 2 8 3 7 4 5 C = 3 9 4 8 I = 2 1 2 1 J = 2 3 6 7 ans = 3 9 4 8

## Explanation

The index returned by both `MIN` and `MAX` is the subscript index *for the dimension along which the min/max value was calculated* (the others are implicitly `1:size(A,d)` for each dimension `d`). `LINDEX` detects which dimension the output index `I` relates to and uses a fast numeric algorithm to calculate the linear indices directly from `I`.

A significantly slower but more intuitive method using `ARRAYFUN`, `NDGRID`, and `SUB2IND` is also included as commented-out code.

Note that there is a very easy way to get the **single** minimum or maximum value from the entire ND array, and its corresponding linear index:

[maxval,linIdx] = max(A(:))

## Example 1: Maximum Magnitude of One Array

Similar to MAX(A), but identifies the largest magnitude.

A = [-5,-2,3,4]; [~,I] = max(abs(A)); J = lindex(size(A),I); A(J)

ans = -5

## Example 2: Minimum Magnitude from Two Matrices

Similar to MIN(A,B), but identifies the smallest magnitude.

A = [+9,+8,-7,-6]; B = [-8,-9,+7,-6]; X = cat(3,A,B); [~,I] = min(abs(X),[],3); J = lindex(size(X),I); X(J)

ans = -8 8 -7 -6

## Example 3: Any Array Size

Of course `LINDEX` works with any size array, not just matrices:

A = randi(99,8,6,4,2); [C,I] = max(abs(A),[],3); J = lindex(size(A),I); isequal(C,A(J))

ans = 1