1.0

1.0 | 2 ratings Rate this file 3 Downloads (last 30 days) File Size: 1.25 KB File ID: #27622

a short code for creating a random (1,-1) matrix

by Changqing Xu

 

15 May 2010

This is a very short code file for creating a random matrix whose entries are either 1 or -1.

| Watch this File

File Information
Description

I have no idea whether this is the first one, but I am pretty sure that you guys can fully understand what can be done by this short and concise matlab code, that is, to generate a random matrix of any given order, with entries randomly chosen from {1,-1}. In fact, the code can be extended to produce any random matrix whose elements are randomly chosen from any dyadic set ,say, {a,b}. The work was originated and inspired by the blog of Terence Tao on random matrix (see the webpage:
http://terrytao.wordpress.com/tag/random-matrices/)
and a talk "Discrete random matrices " by P.M.Wood from Stanford on the BADMath day of Spring 2010, San Jose,CA.
The running of the code is very fast, as you can find. But it will sharply slow down and display "inf" on your command window if you
put "det" function involved to test its singularity. Sure we may avoid this by using instead a logic function.

MATLAB release MATLAB 7.7 (R2008b)
Tags for This File  
Everyone's Tags
Tags I've Applied
Add New Tags Please login to tag files.
Comments and Ratings (2)
17 May 2010 James Tursa

This submission has the following problems:
1) It uses a double for loop to individually fill in each element of the resulting matrix rather than using vectorized code.
2) It uses the relatively expensive power operator to generate the +1 and -1 values.
3) The H1 line function name does not match the actual function name.
4) A much faster (more than 3x faster) one-liner equivalent to this submission is as follows: floor(rand(n)*2)*2-1
5) There is no provision for non-square or multi-dimensional sizes. Only square 2D sizes are supported.

James Tursa

18 May 2010 Jos (10584)

Indeed poorly coded using an unnecessary double-for loop (with pre-allocation though!), limited to 2D sqaure matrices only.

A vectorized, (too!) simple and flexible approach:

function R = rand01(varargin)
% H1 line goes here
% help goes here
R = 2*(rand(varargin{:})>0.5)-1 ;

Please login to add a comment or rating.
Tag Activity for this File
Tag Applied By Date/Time
random matrix Changqing Xu 17 May 2010 12:18:37
binary Changqing Xu 17 May 2010 12:18:37
singularity Changqing Xu 17 May 2010 12:18:37
determinant Changqing Xu 17 May 2010 12:18:37

Contact us at files@mathworks.com