kaniz
kaniz

Reputation: 23

how to create this matrix without using for loop?

I want to create a N*N matrix A.

when n = 4
2  0 -2  0
2  0  2  0
0  2  0 -2
0  2  0  2

when n = 8
2  0  0  0 -2  0  0  0
2  0  0  0  2  0  0  0
0  2  0  0  0 -2  0  0
0  2  0  0  0  2  0  0
0  0  2  0  0  0 -2  0
0  0  2  0  0  0  2  0
0  0  0  2  0  0  0 -2
0  0  0  2  0  0  0  2

I can create this using nested for loop, but how to achieve it more efficiently? Are there any methods without for loop?

Thanks

Upvotes: 2

Views: 118

Answers (2)

Divakar
Divakar

Reputation: 221574

Here's one way with bsxfun -

A = zeros(n);
idx = bsxfun(@plus,[0:(n/2)-1]*((n+3)-1),[1:2].');
A(idx) = 2;
A(idx+numel(A)/2) = -2;

Sample runs -

Case #1 :

>> n = 4;
>> A
A =
     2     0    -2     0
     2     0    -2     0
     0     2     0    -2
     0     2     0    -2

Case #2 :

>> n = 8;
>> A
A =
     2     0     0     0    -2     0     0     0
     2     0     0     0    -2     0     0     0
     0     2     0     0     0    -2     0     0
     0     2     0     0     0    -2     0     0
     0     0     2     0     0     0    -2     0
     0     0     2     0     0     0    -2     0
     0     0     0     2     0     0     0    -2
     0     0     0     2     0     0     0    -2

Upvotes: 1

Wauzl
Wauzl

Reputation: 971

You can do it like that:

[reshape([repmat([ 2;2;zeros(n,1)],n/2-1,1); 2;2],n,n/2)   ...
 reshape([repmat([-2;2;zeros(n,1)],n/2-1,1);-2;2],n,n/2) ]

This only will work, if n is a power of two, obviously.

[EDIT] It might be faster to use

[reshape([repmat([ 2;2;zeros(n,1)],n/2-1,1); 2;2;       ...
          repmat([-2;2;zeros(n,1)],n/2-1,1);-2;2] ,n,n) ]

[EDIT2] This is only a good idea, if you have n of moderate size. If you need really big matrices, you should use sparse matrices. In this case a loop is what you want.

Upvotes: 0

Related Questions