Go to the

MLX,M,HTMLversion of this file. Go back to fan’s MEconTools Package, Matlab Code Examples Repository (bookdown site), or Math for Econ with Matlab Repository (bookdown site).

Given a matrix of values, what is the maximum element, what are the row and column indexes of this max element of the matrix.

```
rng(123);
N = 3;
M = 4;
mt_rand = rand(M,N);
disp(mt_rand);
0.6965 0.7195 0.4809
0.2861 0.4231 0.3921
0.2269 0.9808 0.3432
0.5513 0.6848 0.7290
[max_val, max_idx] = max(mt_rand(:));
[max_row, max_col] = ind2sub(size(mt_rand), max_idx)
max_row = 3
max_col = 2
```

There is a matrix with N columns, and M rows, with numerical values. Generate a table of sorted index, indicating in each column which row was the highest in value, second highest, etc. (1) sort each column. (2) show the row number from descending or ascending sort for each column as a matrix.

```
% Create a 2D Array
rng(123);
N = 2;
M = 4;
mt_rand = rand(M,N);
disp(mt_rand);
0.6965 0.7195
0.2861 0.4231
0.2269 0.9808
0.5513 0.6848
```

Use the maxk function to generate sorted index:

```
% maxk function
[val, idx] = max(mt_rand);
disp(val);
0.6965 0.9808
disp(idx);
1 3
```

There is a matrix with N columns, and M rows, with numerical values. Generate a table of sorted index, indicating in each column which row was the highest in value, second highest, etc. (1) sort each column. (2) show the row number from descending or ascending sort for each column as a matrix.

```
% Create a 2D Array
rng(123);
N = 2;
M = 4;
mt_rand = rand(M,N);
disp(mt_rand);
0.6965 0.7195
0.2861 0.4231
0.2269 0.9808
0.5513 0.6848
```

Use the maxk function to generate sorted index:

```
% maxk function
[val, idx] = maxk(mt_rand, M);
disp(val);
0.6965 0.9808
0.5513 0.7195
0.2861 0.6848
0.2269 0.4231
disp(idx);
1 3
4 1
2 4
3 2
```