How to get a diagonal matrix from A vector
I have a column:
0.0677
0.0584
0.0487
0.0453
0.0394
开发者_如何学GoWhat instruction would get the following output
0.0677 0 0 0 0
0 0.0584 0 0 0
0 0 0.0487 0 0
0 0 0 0.0453 0
0 0 0 0 0.0394
diag is the normal MATLAB solution (as pointed out by posdef.) Thus
D = diag(vec);
gives you a matrix with diagonal elements as needed.
Perhaps better in some applications is to create a sparse matrix, since a diagonal matrix is quite sparse. So if you are doing matrix multiplies this will greatly help in reducing the number of unnecessary operations.
n = length(vec);
D = spdiags(vec(:),0,n,n);
If you truly wanted to do the assignment in an explicit form, use a single linear index like this:
n = length(vec);
D = zeros(n);
D(cumsum([1,repmat(n+1,1,n-1)])) = vec;
Or you could use the sub2ind function to convert a set of indices into a single index.
If I remember correctly there's a command called something like diag(A)
Edit: here you go, some documentation on the diag
http://www.mathworks.com/help/techdoc/ref/diag.html
pay particular attention to the quote:
X = diag(v) puts v on the main diagonal, same as above with k = 0.
The following gives the diagonal matrix D
whose diagonal is the vector vec
. It is written in a vectorized fashion in MATLAB.
D = zeros(numel(vec));
[I,J] = ind2sub(size(D),1:numel(D));
ind = [I(:) J(:)];
ind = find(ind(:,1)==ind(:,2));
D(ind) = vec;
Well, obviously you can do it in a C-like way. Right now I can't figure out more elegant solution.
vector;%Your vector
vec_length = length(vector);
A = zeros(vec_length);
for i=1:vec_length
A(i,i) = vector(i);
end;
精彩评论