Variable number of input matrices in a function

I want to change the code below so the function blkdiag can take on any number of matrices A, based on the value of N.
N = 3;
A_1 = sparse(1:N,1:N,-1*ones(N,1),N,N+1);
A_2 = sparse(1:N,2:N+1,1*ones(N,1),N,N+1);
A = A_1+A_2;
out = full(blkdiag(A,A,A))
So suppose N=4, then
out = full(blkdiag(A,A,A,A))
And so on.
How can I create a variable input for this function, based on a value?
Thanks,
Tim

3 件のコメント

madhan ravi
madhan ravi 2019 年 2 月 4 日
編集済み: madhan ravi 2019 年 2 月 4 日
A = {A_1+A_2};
A=repelem(A,N);
out = full(blkdiag(horzcat(A{:}))) % or
out = full(blkdiag(vertcat(A{:})))
Tim de Reijer
Tim de Reijer 2019 年 2 月 4 日
編集済み: Tim de Reijer 2019 年 2 月 4 日
[1]
Your solution does not give the wanted answer.
full(blkdiag(A,A)) results in
-1 1 0 0 0 0 0 0
0 -1 1 0 0 0 0 0
0 0 -1 1 0 0 0 0
0 0 0 0 -1 1 0 0
0 0 0 0 0 -1 1 0
0 0 0 0 0 0 -1 1
While full(blkdiag(repmat(A,1,2))) gives
-1 1 0 0 -1 1 0 0
0 -1 1 0 0 -1 1 0
0 0 -1 1 0 0 -1 1
[2]
Neither full(blkdiag(horzcat(A{:}))) nor full(blkdiag(vertcat(A{:}))) produces the same result as well..
madhan ravi
madhan ravi 2019 年 2 月 4 日
編集済み: madhan ravi 2019 年 2 月 4 日
True , apologies didn't verify the results.

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

 採用された回答

Guillaume
Guillaume 2019 年 2 月 4 日

0 投票

N = 4;
A_1 = sparse(1:N,1:N,-1*ones(N,1),N,N+1);
A_2 = sparse(1:N,2:N+1,1*ones(N,1),N,N+1);
A = A_1+A_2;
blkdiaginputs = repelem({A}, N); %put your inputs in a cell array
out = full(blkdiag(blkdiaginputs{:})) %and convert the cell array into a comma-separated list

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeMultidimensional Arrays についてさらに検索

質問済み:

2019 年 2 月 4 日

回答済み:

2019 年 2 月 4 日

Community Treasure Hunt

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

Start Hunting!

Translated by