Getting introduced to Matlab

There was a time when I thought Matlab is a tool used by engineers. Is it even possible for a student of humanities to get access to such tools ? It is and there are academic licenses.

Matrix

matrix = zeros(10,10);

matrix(1,2) = 3
matrix(2,2) = 30
matrix(1,3) = 2
matrix(4,3) = 14
matrix(5,2) = 199
matrix(6,2) = 733

\begin{bmatrix} 0 & 3 & 2 & 0 & 0\\ 0 & 30 & 0 & 0 & 0\\ 0 & 0 & 0 & 0 & 0\\ 0 & 0 & 14 & 0 & 0\\ 0 & 199 & 0 & 0 & 0\\ 0 & 733 & 0 & 0 & 0\\ \end{bmatrix}

Maximum value from a matrix
[max_value, node] = max(matrix(:));

fprintf ('Maximum value is %d and node is %d\n', max_value, node);

node seems to be a reference to the element which is used below to get the row and column using ind2sub.


[i, j] = ind2sub(size(matrix), node);

fprintf ('Row is %d and column is %d\n', i, j);

sub2ind gives the linear indice of the element when we have the row and column of the element.


linearindice = sub2ind(size(matrix), 1, 2);

fprintf ('Linear Indice is %d \n', linearindice);

Sort

I get the sorted matrix and also the matrix of indices of the sorted elements. Very useful.


[values, indices] = sort( matrix );
Sorted values

\begin{bmatrix} 0 & 0 & 0 & 0 & 0\\ 0 & 0 & 0 & 0 & 0\\ 0 & 3 & 0 & 0 & 0\\ 0 & 30 & 0 & 0 & 0\\ 0 & 199 & 2 & 0 & 0\\ 0 & 733 & 14 & 0 & 0\\ \end{bmatrix}

Indices of sorted values

\begin{bmatrix} 1 & 3 & 2 & 1 & 1\\ 2 & 4 & 3 & 2 & 2\\ 3 & 1 & 5 & 3 & 3\\ 4 & 2 & 6 & 4 & 4\\ 5 & 5 & 1 & 5 & 5\\ 6 & 6 & 4 & 6 & 6\\ \end{bmatrix}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: