import numpy as np
# sow a fix seed to make trial and error more predictable
# create a 10 x 3 NumPy array
a = np.random.rand(10,3)
# do the fancy indexing: for each row, extract the element that is closest to 0.5
a2 = a[np.arange(a.shape[0]), np.argsort(np.abs(a - 0.5))[:,0]]
View fourier.html
<script src="//"></script>
<script src="//"></script>
<script src="//"></script>
<script src="//"></script>
# clean up kernel
%reset -f
# This is a bit of magic to make matplotlib figures appear inline in the notebook
# rather than in a new window.
%matplotlib inline
# Some more magic so that the notebook will reload external python modules;
# see
%load_ext autoreload

Exercise: Tiling for array creation

Skim through the documentation for np.tile, and use this function to construct the array:

[[4, 3, 4, 3, 4, 3],
 [2, 1, 2, 1, 2, 1],
 [4, 3, 4, 3, 4, 3],
 [2, 1, 2, 1, 2, 1]]

This example illustrate the use of Python generator. (it's like callback function in JavaScript - sort of.)

Example 1

Create a matrix and print result:

M = [[1,2,3],    # this row sum to 6
     [4,5,6],    # this row sum to 15
     [7,8,9]]    # this row sum to 24

Say we want to concatenate elements within a JavaScript array (or Python list). i.e.

  • Input: an array that looks like this ['hello', 'world', '123', '!!!']
  • Process: concatenate the string elements within the array
  • Output: hello world 123 !!!

This post shows the similarity (and difference) of the JavaScript and Python syntax. (in case you start using JavaScript but from a Python background. Or vice versa, start using Python but from a JavaScript background)

JavaScript Solution

View wordpress-menu
<button class="menu-toggle"><?php _e( 'Primary Menu', 'twentyfourteen' ); ?></button>

Say we have an array (in JavaScript term) or list (in Python term), this article illustrate a simple functional programming example. i.e.

Input: [1, 2, 3, 4, 5]
Process: square each element
Output: [1, 4, 9, 16, 25]

JavaScript Solution


In Octave, the string manipulation function strtok() can be very handy for scanning through words in a long sentence.

In the following example, we have a sentence:

'hello world how are you'

Assuming all words are separated by a white space, we can repeat this command to extract (1) the word string tok and the remaining sentence s.


Whilst working through the many (Octave) coding assignment from Andrew Ng's Stanford Machine Learning course, a common problem that I have to solve revolves around this:

Given a Matrix A with m rows, and n columns find the mininum (or maximum) value and the associated row and column number

This article summarises my solution to this problem (which, hopefully this will also come in hadny to you!). Note that Octave index start from 1 (instead of 0).

Sample Matrix

Say we have a Matrix A that look like this: