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

 Akzeptierte Antwort

Walter Roberson
Walter Roberson am 18 Apr. 2014

1 Stimme

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

Weitere Antworten (3)

Andrei Bobrov
Andrei Bobrov am 18 Apr. 2014
Bearbeitet: Andrei Bobrov am 18 Apr. 2014

2 Stimmen

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 Kommentar

Jos (10584)
Jos (10584) am 18 Apr. 2014
The old-school (fast) way of run length decoding :-)

Melden Sie sich an, um zu kommentieren.

Jos (10584)
Jos (10584) am 18 Apr. 2014

1 Stimme

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 Kommentar

Jos (10584)
Jos (10584) am 18 Apr. 2014
Bearbeitet: Jos (10584) am 18 Apr. 2014
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{:}])

Melden Sie sich an, um zu kommentieren.

Osman mamun
Osman mamun am 18 Apr. 2014

0 Stimmen

thanks, i was looking for something like repmat.

Kategorien

Community Treasure Hunt

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

Start Hunting!

Translated by