1

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?

SecretAgentMan
  • 2,856
  • 7
  • 21
  • 41
becs
  • 73
  • 7
  • Here they're used for selecting columns of `x0`. You might want to consider checking out the [documentation](https://www.mathworks.com/help/matlab/ref/colon.html) for some more details. – Julius May 29 '19 at 18:59
  • @Julius I'd say the colon in this case is selecting the rows of `x0` (all in this case), and not the column. You indeed end up with a column vector. – rinkert May 29 '19 at 19:11
  • @rinkert in the end, yes. Here `x0(:, 1)` selects a column, and `x0(:)` reshapes `x0` into a single column vector. – Julius May 29 '19 at 19:15

1 Answers1

3

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

SecretAgentMan
  • 2,856
  • 7
  • 21
  • 41