Stefan Hansen
Stefan Hansen

Reputation: 641

Creating a specific matrix

Suppose I have variables

local a=10
local b=1
local c=0.25

where a necessarily is an integer. Now, how do I create an a times a matrix whose diagonal elements are all equal to b and whose off-diagonal elements are all equal to c? I'm not very familiar with matrix in Stata language, so I'm hoping anyone can help me out here. Thanks in advance.

Upvotes: 0

Views: 527

Answers (1)

Nick Cox
Nick Cox

Reputation: 37368

. local a = 10

. local b = 1

. local c = 0.25

. matrix A = `b' * I(`a')

. mat li A

symmetric A[10,10]
     c1   c2   c3   c4   c5   c6   c7   c8   c9  c10
r1    1
r2    0    1
r3    0    0    1
r4    0    0    0    1
r5    0    0    0    0    1
r6    0    0    0    0    0    1
r7    0    0    0    0    0    0    1
r8    0    0    0    0    0    0    0    1
r9    0    0    0    0    0    0    0    0    1
r10    0    0    0    0    0    0    0    0    0    1

. matmap A A , m(cond(@ == 0, 0.25, @))

. mat li A

symmetric A[10,10]
     c1   c2   c3   c4   c5   c6   c7   c8   c9  c10
r1    1
r2  .25    1
r3  .25  .25    1
r4  .25  .25  .25    1
r5  .25  .25  .25  .25    1
r6  .25  .25  .25  .25  .25    1
r7  .25  .25  .25  .25  .25  .25    1
r8  .25  .25  .25  .25  .25  .25  .25    1
r9  .25  .25  .25  .25  .25  .25  .25  .25    1
r10  .25  .25  .25  .25  .25  .25  .25  .25  .25    1

Here matmap must be downloaded from SSC using ssc inst matmap.

By the way, the locals are not needed here. You can just enter your constants as such.

Upvotes: 5

Related Questions