Showing posts with label Matlab. Show all posts
Showing posts with label Matlab. Show all posts

Matlab: Sort 2D array with respect to one column

sort function in Matlab, sorts matrix columns independently.
But,
B = sortrows(A, column) sorts the matrix based on the columns specified in the vector column. 

Example:


>> A = [2 10; -1 20; 5 40]

A =

     2    10
    -1    50
     5    15

>> sortrows(A, 1)

ans =

    -1    50
     2    10
     5    15

>> sortrows(A, 2)

ans =

     2    10
    -1    50
     5    15



MATLAB: String tokenizer, string split

myStr = 'one_two_three';
pieces = regexp(myStr , '_', 'split')

%Output would be an pieces array with 3 elements.
pieces =

    'one'    'two'    'three'

Matlab: Vector product, multiply 2 column matrices, "element-wise" multiplication

If we have 2 column matrices A, B.
>>A = [10;20;30]
A =
10
20
30

>> B = [1;2;3]
B =
1
2
3

>> A+B
ans =
11
22
33

>> A*B
??? Error using ==> mtimes
Inner matrix dimensions must agree.

In order to perform "element-wise" operations, we have to use ".", so for multiplication ".*", division "./"

>> A.*B
ans =
10
40
90

>> A./B
ans =
10
10
10

Python contextlib for Timing Python code

If you've ever found yourself needing to measure the execution time of specific portions of your Python code, the `contextlib` module o...