Create matrix with double rows of [-1 1]

Hey guys, I want to create a matrix which looks the following:
-1 0 0 0
1 0 0 0
0 -1 0 0
0 1 0 0
0 0 -1 0
0 0 1 0
0 0 0 -1
0 0 0 1
and so on. Does anyone know a good way to do that? Maybe there is a helpful command for that :)
Thanks a lot :)
Oh, sorry, an edit:
I would also have an even more complex matrix, which would look the following...
0 0 0 0
-1 0 0 0
0 1 0 0
0 -2 0 0
0 0 2 0
0 0 -3 0
0 0 0 3
0 0 0 -4
Any suggestions? :)

 採用された回答

Ben11
Ben11 2014 年 7 月 10 日
編集済み: Ben11 2014 年 7 月 10 日

0 投票

Simple answer:
clear all
clc
A = zeros(8,4)
for i =2:2:size(A,1)
A(i-1,i/2) = (i/2)-1;
A(i,i/2) = -i/2;
end
A
A =
0 0 0 0
-1 0 0 0
0 1 0 0
0 -2 0 0
0 0 2 0
0 0 -3 0
0 0 0 3
0 0 0 -4
There is probably a more compact way to do it though :)

2 件のコメント

Leonard
Leonard 2014 年 7 月 10 日
okay, thanks. That is really a good solution and quite fast! Thanks a lot again!
Ben11
Ben11 2014 年 7 月 10 日
My pleasure!

サインインしてコメントする。

その他の回答 (2 件)

Andrei Bobrov
Andrei Bobrov 2014 年 7 月 10 日

2 投票

1.
out1 = kron(eye(4),[-1;1]);
2.
out2 = kron(eye(4),[1;1]);
out2(out2>0) = bsxfun(@plus,[1;-1]*(1:4),[-1;0]);

1 件のコメント

Leonard
Leonard 2014 年 7 月 11 日
This is really handy, thanks!!

サインインしてコメントする。

José-Luis
José-Luis 2014 年 7 月 10 日
編集済み: José-Luis 2014 年 7 月 10 日

1 投票

numDiag = 4;
numVal = 2;
val1 = eye(numDiag);
val2 = val1;
val1(val1==1) = 0:3;
val2(val2 == 1) = -1:-1:-4;
your_mat = cat(3,val1,val2);
reshape(shiftdim(your_mat,2),[numDiag*numVal, numDiag])

2 件のコメント

Ben11
Ben11 2014 年 7 月 10 日
Nicely done @José-Luis!
José-Luis
José-Luis 2014 年 7 月 10 日
Thanks!

サインインしてコメントする。

カテゴリ

ヘルプ センター および File ExchangeCreating and Concatenating Matrices についてさらに検索

質問済み:

2014 年 7 月 10 日

コメント済み:

2014 年 7 月 11 日

Community Treasure Hunt

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

Start Hunting!

Translated by