how to create a 3D diagonal matrix from a 2D matrix ?

Hi, I have a 2D matrix A=rand(3,5) and i want to create a 3D matrix B, where
B(1,:,:) = diag(A(1,:)) ; B(2,:,:) = diag(A(2,:)) ; B(3,:,:) = diag(A(3,:))
so the final size of B is expected to be 3x5x5
I am looking for a command to calculate B without passing through loops or for .
thanks

4 Comments

I am confused about the point of this....
B = rand(3,5,5);
C = rand(3,5,5);
D = rand(3,5);
try
x1 = (B-C).\D % Error
catch
disp('first one made an error!')
x2 = (B-C)\D % Error
end
What are you trying to do again??
yasser
yasser on 23 Aug 2012
Edited: yasser on 23 Aug 2012
My previous problem was the following:
the dimensions of B and C are 380x380 and the dimensions of D = 380x1
A = rand(380,1); B = diag(A); C = rand(380,380); D = rand(380,1); X = inv(B-C)*D; cost = sum(X);
the following step is to vectorize my input variable A from 1x380 to 100x380, this way i compute an array of cost functions X.
any help is appreciated
But that is not what you wrote above! You clearly have B and C as 3D and the equation you show produces an error. So which is it? 3D or 2D? How are we to help if you say 3D one time and 2D the next??
your comment is correct, but that's another issue to solve. I will open another thread to explain in details my problem.

Sign in to comment.

 Accepted Answer

This is a little kludgy, but it works. I deliberately did not simplify some of the operations, to keep it clearer where the 5's and 3's come in.
A = rand(3,5);
linearIndex = logical([ones(3*1,1); repmat([zeros(3*5,1); ones(3*1,1)],[5-1 1])]);
B = zeros(3,5,5);
B(linearIndex) = A(:);

1 Comment

This command is working perfectly. However is it time-cost efficient for a global optimization tool where the dimensions of B are 100x380x380. It looks a bit costly ?

Sign in to comment.

More Answers (1)

So each slice of B should contain a column vector (like you have above)? Why not just use a FOR-loop? or bsxfun? For example:
x = bsxfun(@minus,C,A).\D
Actually, bsxfun won't fill in zeros here so a for-loop is your best bet.

2 Comments

loop for wont help much, because i have simplified my problem to a 3x5x5, my real problem is much bigger 100x380x380.
And how is a for-loop not perfectly applicable to that?

Sign in to comment.

Categories

Community Treasure Hunt

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

Start Hunting!