Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

Thread Subject:
Random Matrix help

Subject: Random Matrix help

From: Hend

Date: 6 May, 2013 16:27:09

Message: 1 of 4

I've never done any programming before so excuse me if what I'm asking is too simple to even be asked. I'm trying to construct a random nxn matrix that is symmetric and has entries of either 1 or -1 on the off-diagonals and 0s on the diagonal. Something tells me this is really easy but I can't figure it out.

I have this so far

n=5;
A=rand(n);
A=(A+A')/2;
round(A)

But this only gives me entries of either 0 or 1 and I cannot figure out what to do to make the entries on the diagonal 0s.

Thanks.

Subject: Random Matrix help

From: Bruno Luong

Date: 6 May, 2013 17:37:08

Message: 2 of 4

>> n=5

n =

     5

>> A=tril(round(rand(n)))

A =

     0 0 0 0 0
     0 1 0 0 0
     0 1 1 0 0
     1 1 0 1 0
     0 1 1 1 0

>> A=A+A'

A =

     0 0 0 1 0
     0 2 1 1 1
     0 1 2 0 1
     1 1 0 2 1
     0 1 1 1 0

>> A(A==0) = -1

A =

    -1 -1 -1 1 -1
    -1 2 1 1 1
    -1 1 2 -1 1
     1 1 -1 2 1
    -1 1 1 1 -1

>> A(1:n+1:end) = 0

A =

     0 -1 -1 1 -1
    -1 0 1 1 1
    -1 1 0 -1 1
     1 1 -1 0 1
    -1 1 1 1 0

% Bruno

Subject: Random Matrix help

From: Steven_Lord

Date: 6 May, 2013 17:56:20

Message: 3 of 4



"Bruno Luong" <b.luong@fogale.findmycountry> wrote in message
news:km8po4$9m$1@newscl01ah.mathworks.com...

*snip Bruno's approach*

Not bad. Another approach:

n = 5;
A = sign(randn(n));
% Technically you'd need to replace any 0's in A with -1 or 1
% The odds of that happening are so small I'm going to neglect this step for
the example
A = triu(A, 1)+triu(A, 1).'

--
Steve Lord
slord@mathworks.com
To contact Technical Support use the Contact Us link on
http://www.mathworks.com

Subject: Random Matrix help

From: Bruno Luong

Date: 6 May, 2013 18:40:13

Message: 4 of 4

"Steven_Lord" <slord@mathworks.com> wrote in message <km8qs6$4jt$1@newscl01ah.mathworks.com>...

> % The odds of that happening are so small I'm going to neglect this step for
> the example

I propose to remove the chance of oddity entirely, and furthermore gaining some speed by using RAND rather than RANDN.

n = 5;
A = triu(2*round(rand(n))-1,1);
A = A + A'

% Bruno

Tags for this Thread

What are tags?

A tag is like a keyword or category label associated with each thread. Tags make it easier for you to find threads of interest.

Anyone can tag a thread. Tags are public and visible to everyone.

Contact us