i want to form a diagonal matrix from two matrix, one contains the value of diagonal elements and other contains how many times it should occur.For example: a=[5 10 15] and b=[2 2 2] so the resultant matrix should look like r=[5 0 0 0 0 0;0 5 0 0 0 0;0 0 10 0 0 0;0 0 0 10 0 0;0 0 0 0 15 0;0 0 0 0 0 15]; But the problem is a and b can vary depending upon the situation or user input.
can i form such a matrix? I will highly appreciate any kind of suggestion.
Thanks, Mamun

 채택된 답변

Walter Roberson
Walter Roberson 2014년 4월 18일

1 개 추천

"for" loop around repmat() in order to build the diagonal vector, and then diag() that.
Or just use a nested "for" loop.

추가 답변 (3개)

Andrei Bobrov
Andrei Bobrov 2014년 4월 18일
편집: Andrei Bobrov 2014년 4월 18일

2 개 추천

a=[5 10 15 20];
b=[2 1 4 3];
x = cumsum(b);
v = zeros(x(end),1);
v(x-b+1) = 1;
out = diag(a(cumsum(v)));

댓글 수: 1

Jos (10584)
Jos (10584) 2014년 4월 18일
The old-school (fast) way of run length decoding :-)

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

Jos (10584)
Jos (10584) 2014년 4월 18일

1 개 추천

A = [5 10 15 20] ;
B = [2 1 4 3] ;
C = arrayfun(@(k) A(k)*eye(B(k)),1:numel(A),'un',0) ;
result = blkdiag(C{:})

댓글 수: 1

Jos (10584)
Jos (10584) 2014년 4월 18일
편집: Jos (10584) 2014년 4월 18일
or using REPMAT and DIAG (which is therefore also, probably, more memory efficient):
A = [5 10 15 20] ;
B = [2 1 4 3]
C = arrayfun(@(k) repmat(A(k),1,B(k)), 1:numel(A),'un',0) ;
result2 = diag([C{:}])

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

Osman mamun
Osman mamun 2014년 4월 18일

0 개 추천

thanks, i was looking for something like repmat.

카테고리

도움말 센터File Exchange에서 Operating on Diagonal Matrices에 대해 자세히 알아보기

질문:

2014년 4월 18일

댓글:

2014년 4월 18일

Community Treasure Hunt

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

Start Hunting!

Translated by