becs
becs

Reputation: 83

What is the colon operator doing here?

What are these lines of code doing?

x0 = rand(n,2)
x0(:,1)=W*x0(:,1)
x0(:,2)=H*x0(:,2)
x0=x0(:)

Is this just one big column vector?

Upvotes: 1

Views: 151

Answers (1)

SecretAgentMan
SecretAgentMan

Reputation: 2854

I'd encourage you to take a MATLAB Tutorial as indexing arrays is a fundamental skill. Also see Basic Concepts in MATLAB. Line-by-line descriptions are below to get you started.

What are these lines of code doing?

Let's take this line by line.
1. This line uses rand() to generate an n x 2 matrix of uniform random numbers (~U(0,1)).
x0 = rand(n,2) % Generate nx2 matrix of U(0,1) random numbers

2. Multiply the first column by W
In this case, x0(:,1) means take all rows of x0 (the colon in the first argument) and the 1st column (the 1). Here, the * operator indicates W is a scalar or an appropriately sized array for feasible matrix multiplication (my guess is a scalar). The notation .* can be used for element-by-element multiplication; see here and here for more details.
x0(:,1)=W*x0(:,1) % Multiply (all rows) 1st column by W

3. Multiply the first column by H.
Using similar logic as #2.
x0(:,2)=H*x0(:,2) % Multiply (all rows) 2nd column by H

4. Force column
The x0(:) takes the array x0 and forces all elements into a single column.

From the documentation for colon:

A(:) reshapes all elements of A into a single column vector. This has no effect if A is already a column vector.


A related operation is forcing a row vector by combining this with the transpose operator.
For example, try the following: x0(:).'

x0 = x0(:)       % Force Column
x0 = x0(:).'     % Force Row

Related Posts:
What is Matlab's colon operator called?
How does MATLAB's colon operator work?
Combination of colon-operations in MATLAB

Upvotes: 3

Related Questions