Monday, 15 April 2013

matlab - Creating a diagonal matrix (higher dimension) -



matlab - Creating a diagonal matrix (higher dimension) -

i have n* m matrix, a. i'd create next m* m*n matrix, b

for j=1:n b(:,:,j)=diag(a(j,:)); end

how do without having loop?

thanks

update: i've edited question prepare typos in sample code.

i'm sure illustration code contains couple of typos, since matrix a serves no purpose, nor looping subscript j. however, seems reasonably trying inquire is: how build 3d array each diagonal (moving along 3rd dimension) row a, without doing loop?

if correct, 1 reply follows:

%# loop-less solution soln2 = zeros(m, m, n); soln2(bsxfun(@plus, (1:m+1:m*m)', (0:m^2:(n-1)*m^2))) = a';

essentially i've done pre-allocate solution 3d array, , used bsxfun build linear index of diagonals, moving along 3rd dimension. assign transpose of a (because want rows not columns) linear index in solution array.

note, i've pasted sample code testing purposes below. please verify interpretation of loop-based solution after.

%# set parameters , create random matrix n = 3; m = 4; = randi(5, n, m); %# loop based solution soln1 = nan(m, m, n); n = 1:n soln1(:,:,n) = diag(a(n,:)); end %# loop-less solution soln2 = zeros(m, m, n); soln2(bsxfun(@plus, (1:m+1:m*m)', (0:m^2:(n-1)*m^2))) = a';

matlab

No comments:

Post a Comment