How can I can I create a square diagonal matrix and insert variables into it?

Hello,
I need to create a 500x500 matrix that looks like this
[0 0 0 0 0 x
0 0 0 0 x 0
0 0 0 x 0 0
0 0 y 0 0 0
0 y 0 0 0 0
y 0 0 0 0 0 ]
now i know that i can use eye(0,0) command and use the fliplr() to create an inverse identity matrix. but i just need to know how to add variables into it.....
any ideas?
your help is appreciated
THANK YOU :)

2 Comments

Does only half the values are x and rest y in the diagonal matrix?

Sign in to comment.

 Accepted Answer

A=zeros(6)
[n,m]=size(A);
idx=sub2ind([n m],1:n,n:-1:1)
x=5;
y=10;
A(idx)=[x x x y y y ]

3 Comments

thank you Azzi... but I need to do this on a 500x500 matrix.. is there a way?? thanks for your help :)
A=zeros(500)
[n,m]=size(A);
idx=sub2ind([n m],1:n,n:-1:1)
x=5;
y=10;
A(idx)=[repmat(x,1,250) repmat(y,1,250) ]

Sign in to comment.

More Answers (1)

Unless you need something outlandishly fast or special I'd go for KISS:
M = flipud(diag([y y y y x x x x]));
HTH

4 Comments

Thanks a lot :)
Thats a great one björn. is it possible to do it for a 500x500 matrix?? thank you
Using Bjorn code
M = flipud(diag([repmat(x,1,250) repmat(y,1,250)]));

Sign in to comment.

Categories

Asked:

on 31 Jan 2014

Commented:

on 1 Feb 2014

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!