Code covered by the BSD License  

Highlights from
A more short code forgenerating a random matrix A of (1,-1);

1.0

1.0 | 1 rating Rate this file 2 Downloads (last 30 days) File Size: 1.09 KB File ID: #27645

A more short code forgenerating a random matrix A of (1,-1);

by Binbin Qi

 

18 May 2010

A more short code for generating a random matrix A of (1,-1),no loop

| Watch this File

File Information
Description

A more short code for generating a random matrix A of (1,-1),no loop

MATLAB release MATLAB 7.10 (2010a)
Tags for This File  
Everyone's Tags
Tags I've Applied
Add New Tags Please login to tag files.
Comments and Ratings (4)
18 May 2010 James Tursa

This submission has the following problems:
1) It uses the relatively expensive power operator and bsxfun to generate the +1 and -1 values.
3) No H1 line.
4) No help.
5) A much faster (more than 3x faster) one-liner equivalent to this submission is as follows: floor(rand(n)*2)*2-1
6) There is no provision for multi-dimensional sizes. Only 2D sizes are supported.

James Tursa

18 May 2010 James Tursa

Typo. The one-liner equivalent is: floor(rand(m,n)*2)*2-1

19 May 2010 Binbin Qi

thank you,I think the following is efficient
A=round(rand(m,n))*2-1;
A=floor(rand(m,n)*2)*2-1;
A=fix(rand(m,n)*2)*2-1;
A=randi([0,1],m,n)*2-1;

19 May 2010 Matt Fig

A general, ND version could look like:

function A = randmatrix(varargin)
A = floor(rand(varargin{:})*2)*2-1;

The 2D limitation, in addition to the need for usable help, a more descriptive name (something like RANDSIGNONES at least describes more closely what the code produces), and an H1 line prevent the file from being that useful as it now stands.

Please login to add a comment or rating.
Tag Activity for this File
Tag Applied By Date/Time
bsxfun Binbin Qi 18 May 2010 11:02:26
randi Binbin Qi 18 May 2010 11:02:26

Contact us at files@mathworks.com