フィルターのクリア

How to create a specific diagonal Matrix

1 回表示 (過去 30 日間)
Stefano Di Vito
Stefano Di Vito 2018 年 4 月 20 日
コメント済み: Stephen23 2018 年 4 月 20 日
Hi everyone! I'm trying to find the way to write a generic code to obtain a matrix like the one in this example:
if true
A=[1 1 1 0 0 0 0 0 0;0 0 0 1 1 1 0 0 0;0 0 0 0 0 0 1 1 1]
end
To be clearer, i need a code to fill my matrix, which dimension is (T,T^2). In the example i have T=3. I need the general code because i need a matrix for each T i set, and it should respect the criteria of the example. This means that i have, for each row, a ones(1,T) vector that starts when the ones vector of the previous row ends. The first row should start with a ones(1,T) vector, as in the example. It is a sort of diagonal matrix i guess. I need it because it is part of the unequality constraints matrix in a linear program i'm developing. Hope someone could help me! thanks a lot in advance!

回答 (2 件)

Birdman
Birdman 2018 年 4 月 20 日

Try this:

T=3;
for i=1:T
    A(i,:)=circshift([ones(1,T) zeros(1,T^2-T)],T*(i-1));
end
  2 件のコメント
Stefano Di Vito
Stefano Di Vito 2018 年 4 月 20 日
It worked. Thanks a lot, really!
Birdman
Birdman 2018 年 4 月 20 日
You are welcome!

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


Stephen23
Stephen23 2018 年 4 月 20 日
編集済み: Stephen23 2018 年 4 月 20 日

That is exactly what blkdiag is for:

>> V = [1,1,1];
>> blkdiag(V,V,V)
ans =
   1   1   1   0   0   0   0   0   0
   0   0   0   1   1   1   0   0   0
   0   0   0   0   0   0   1   1   1

This is much simpler and much more efficient than trying to write your own code using loops. Remember that MATLAB is a high-level language, so loops are often not the best solution.

  3 件のコメント
Sean de Wolski
Sean de Wolski 2018 年 4 月 20 日
x = repmat({[ones(1, 3)]}, 1, 3)
blkdiag(x{:})
Stephen23
Stephen23 2018 年 4 月 20 日

@Stefano Di Vito: using the method that Sean de Wolski showed. It uses a comma-separated list to provide as many input arguments as you want:

https://www.mathworks.com/help/matlab/matlab_prog/comma-separated-lists.html

https://www.mathworks.com/matlabcentral/answers/320713-how-to-operate-on-comma-separated-lists

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

カテゴリ

Help Center および File ExchangeOperating on Diagonal Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by