How to copy a sub-matrix/vector along diagonal of a larger matrix with varying number of sub-matrices?

조회 수: 3 (최근 30일)
I want to create a matrix below where I copy A = [1 2 3] allow the diagonal of a matrix.
[ 1 2 3 0 0 0 0 0 0 0 0 0
0 0 1 2 3 0 0 0 0 0 0
0 0 0 0 0 0 1 2 3 0 0 0
0 0 0 0 0 0 0 0 0 1 2 3]
I know I can use blkdiag(A ,A, A, A) which will do the job however the number of parameters vary in my code. Sometimes, there may be five A vectors or 20 A vectors that I need to create such a matrix. Let's say this is a variable that the user inputs
How can I do this efficiently in code?
  댓글 수: 2
Sean de Wolski
Sean de Wolski 2013년 3월 8일
I'm not clear, how would result be different with five vectors or twenty?
John
John 2013년 3월 8일
If I wanted 5 vectors, it would be blkdiag(A, A, A, A, A) If I wanted 20 vectors, it would be blkdiag(A, A, A, A....A, A, A)
I don't know how many A vectors I need so the input to blkdiag would change each time.

댓글을 달려면 로그인하십시오.

채택된 답변

Sean de Wolski
Sean de Wolski 2013년 3월 8일
You can use comma-separated list expansion to do this automagically:
n = 20;
A = [1 2 3];
Ac = repmat({A},n,1);
blkdiag(Ac{:})

추가 답변 (3개)

Azzi Abdelmalek
Azzi Abdelmalek 2013년 3월 8일
편집: Azzi Abdelmalek 2013년 3월 8일
a=[1 2 3]
n=5
d=[a zeros(1,numel(a)*(n-1))]
out=cell2mat(arrayfun(@(x) circshift(d,[0 (n-1)*x]),(0:n-1)','un',0))
EDIT
a=[1 2 3]
n=5
d=[a zeros(1,numel(a)*(n-1))]
out=cell2mat(arrayfun(@(x) circshift(d,[0 numel(a)*x]),(0:n-1)','un',0))
  댓글 수: 1
Azzi Abdelmalek
Azzi Abdelmalek 2013년 3월 8일
편집: Azzi Abdelmalek 2013년 3월 8일
There was an error, check this
n=5 % number of matrices
a=[1 2 3]
d=[a zeros(1,numel(a)*(n-1))]
out=cell2mat(arrayfun(@(x) circshift(d,[0 numel(a)*x]),(0:n-1)','un',0))

댓글을 달려면 로그인하십시오.


Azzi Abdelmalek
Azzi Abdelmalek 2013년 3월 8일
편집: Azzi Abdelmalek 2013년 3월 8일
n=10
a=[1 2 3]
s= ['@(x1)blkdiag(x1' sprintf(',x%d',ones(1,n-1)) ')']
blkdiagn=str2func(s)
out=blkdiagn(a)

George Papazafeiropoulos
George Papazafeiropoulos 2013년 3월 8일
e = ones(n,1);
A = full(spdiags([e 2*e 3*e], 0:2, n, n+2))
A = full(spdiags(A, 0:5, n, n+5))
A = full(spdiags(A, 0:8, n, n+8))
George Papazafeiropoulos

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by