2

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

1
  • Check the diag function, this one can create off-diagonal elements as well. Commented Sep 16, 2015 at 8:18

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you so much for your help... :) it works perfectly.
You will like this: kron in recent Matlab versions (from R2014b, maybe earlier) uses bsxfun internally!
@LuisMendo Yes! I think first chappjc told me about this, or he commented on some answer from Ray. Seems like bsxfun is spreading like a good disease all over! ;)
0

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.

1 Comment

thanks for the help... :) I learn how to use reshape and repmat. and it works perfect for the problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.