## Thursday, February 28, 2013

### generate random numbers with a given correlation in matlab

Q. How to generate random numbers with a pre specified correlation in Matlab?

Ans. Use mvnrnd() function.This function takes mean (vector of 1xk), covariance (matrix of k x k), number of points (n). The output is an nxk matrix which corresponds to the multivariate normal distribution with the specified mean, covariance.
```>> n=1000; mu=[-2,2]; sigma=[1 0.5; 0.5 1]; X = mvnrnd(mu, sigma, n);
>> size(X)
ans =
1000           2

>> mean(X)
ans =
-2.0350    2.0157

>> cov(X)
ans =
0.9950    0.4898
0.4898    0.9894

>> plot(X(:,1), X(:,2), '.')
>> grid
```

The problem is underspecified if only the correlation matrix is known. In this case, set the mean to a zero vector, covariance to the given correlation matrix.

Tested in MATLAB 7.14.0.739 (R2012a),  Octave 3.6.2

## Thursday, February 21, 2013

### append a number to a string in matlab

Problem: Given a prefix say 'foo', generate a cell array of strings in Matlab such that each string has a number appended to it.

Ans:
```>> n=5; cas = cellstr([repmat('foo', n, 1), num2str([1:n]')])

cas =

'foo1'
'foo2'
'foo3'
'foo4'
'foo5'
```
Spaces are automatically appended when the appended numbers have wider range.
```>> n=10; cas = cellstr([repmat('foo', n, 1), num2str([1:n]')])

cas =

'foo 1'
'foo 2'
'foo 3'
'foo 4'
'foo 5'
'foo 6'
'foo 7'
'foo 8'
'foo 9'
'foo10'
```
Adding another string at the top of the array is easy
```>> n=10; cas = [{'raju'}; cellstr([repmat('foo', n, 1), num2str([1:n]')])]

cas =

'raju'
'foo 1'
'foo 2'
'foo 3'
'foo 4'
'foo 5'
'foo 6'
'foo 7'
'foo 8'
'foo 9'
'foo10'
```
which can also be done by
```>> n=10; cas = cellstr([repmat('foo', n, 1), num2str([1:n]')]); cas2 = [{'raju'}; cas]

cas2 =

'raju'
'foo 1'
'foo 2'
'foo 3'
'foo 4'
'foo 5'
'foo 6'
'foo 7'
'foo 8'
'foo 9'
'foo10'
```