Search This Blog

Showing posts with label matlab tips. Show all posts
Showing posts with label matlab tips. Show all posts

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, August 23, 2012

kill all the open figures in matlab

The following function can be used to kill all the open figures in Matlab

function kill_figures
  % close all open figures
  delete(findall(0,'Type','figure'));
end
This function comes in handy when doing parametric studies. Say, there is a big chunk of code that generates 10 figures per run. In order to study the effect of a parameter for say 5 cases, we end up generating 50 (=5x10) plots. Once the study is done, this function comes in handy to kill all those figure windows.

Related tips:

To get the handles of all the figures, do
figHandles = findall(0, 'Type', 'figure');


Followers