## Matlab Snippets

Table of Contents |

## Shift matrix

X([2:end 1])

## Behavior of reshape

Conclusion: row first, col second, color third.

Note: row is the 1st dim, col is the 2nd dim, color is the 3rd dim in matlab.

>> A = 1:6 A = 1 2 3 4 5 6 >> reshape(A,2,3) ans = 1 3 5 2 4 6

>> A = repmat(1:4,3,1) A = 1 2 3 4 1 2 3 4 1 2 3 4 >> reshape(A,4,3) ans = 1 2 3 1 2 4 1 3 4 2 3 4 >> reshape(A,2,6) ans = 1 1 2 3 3 4 1 2 2 3 4 4 >> % How to reshape in x axe >> reshape(A.', 6, 2).' ans = 1 2 3 4 1 2 3 4 1 2 3 4

>>I(:,:,1) = [1 1 1;2 2 2]; I(:,:,2) = [3 3 3;4 4 4]; I(:,:,3) = [5 5 5; 6 6 6] I(:,:,1) = 1 1 1 2 2 2 I(:,:,2) = 3 3 3 4 4 4 I(:,:,3) = 5 5 5 6 6 6 >>reshape(I,6,3) ans = 1 3 5 2 4 6 1 3 5 2 4 6 1 3 5 2 4 6 >> reshape(permute(I,[2 1 3]),6,3).' ans = 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5 6 6 6 >> reshape(permute(I,[3 2 1]),3,6) ans = 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5 6 6 6

## Get indices of starting 0 in [1 1 1 0 0 0 1 1 1 0 0]

A = [1 1 1 0 0 0 1 1 1 0 0] % 1 1 1 0 0 0 1 1 1 0 0 conv(A, [1 -1]); % 1 0 0 -1 0 0 1 0 0 -1 0 0 conv(A, [1 -1]) == -1 % 0 0 0 1 0 0 0 0 0 1 0 find(conv(A, [1 -1]) == -1) % 4 10

## uniq() keeping the sequence

e.g., [3 2 1 1 7 6 1 2 3 6] => [3 2 1 7 6]

A = [3 2 1 1 7 6 1 2 3 6] [uniq, ind] = unique(A,'first') uniq = 1 2 3 6 7 ind = 3 2 1 6 5 % ind means uniq == A(ind) [sorted, ind] = sort(ind) sorted = 1 2 3 5 6 ind = 3 2 1 5 4 uniq(ind) ans = 3 2 1 7 6

## Lower triangular matrix into symmetric matrix

A = [1 0 0 1 1 0 1 1 1]; into B = [1 1 1 1 1 1 1 1 1];

B = A + tril(A, -1).';

## Normalize matrix

by colsum

A = ones(3, 4); A ./ repmat(sum(A, 2), 1, 4);

by row sum

A ./ repmat(sum(A, 1), 3, 1);

by total sum

A ./ repmat(sum(sum(A)), 3, 4);

## Hash array

struct would be most appropriate

hash = struct('key1', val1, 'key2', val2) hash.key1