问题描述:

I have a vector v of size 1 x 5, and a diagonal matrix D of size 5 x 5. In my example, I have v = [0 1 2 3 4].

First question: I want to put the vector v on the diagonal of D, so that D(1,1) = 0, D(2,2) = 1, D(3,3) = 2, D(4,4) = 3 and D(5,5) = 4.

I wrote a matlab code for this but I am sure that there is another automatic method much less expensive in computation.

So what I wrote (and to be optimized from you) is the following:

 ii = 1;

for a = 1 : size(D,1)

for b = 1 : size(D,2)

if(a == b)

D(a,b) = v(1, ii);

ii = ii + 1;

end

end

end

Second Question: After finishing the first question, I need now to check if the diagonal values of D are equal to zero. If I can find (in an automatic way) a value on the diagonal of D is equal to zero, so replace it by 0.001.

In fact this can be written in a lot of manners, for example:

for a = 1 : size(D,1)

for b = 1 : size(D,2)

if(a == b)

if(D(a,b) == 0)

D(a,b) = 0.001;

end

end

end

end

But I need another automatic method which can be very cheap in terms of computations.

Any help will be very appreciated!

网友答案:

You're making your life harder than necessary: you don't need two loops (one would be enough), since you only need to walk along the diagonal. You actually don't need any loop, here; only the diag function.

Anyway, it may be easier to replace zero entries in a copy of v, and then use it to build the diagonal matrix:

v2 = v;              % create a copy of v (if needed)
v2(v2 == 0) = 1e-3;  % replace zero entries

Note: If the entries you want to replace are not exactly zero, but small floating-point values, you'll need something like this instead:

v2(abs(v2) < epsilon) = 1e-3;  % replace zero entries

where epsilon is the threshold below which, as far as you're concerned, the entry is close enough to zero that it can be neglected.


Then, since you write that D already is a diagonal matrix, you can simply overwrite it:

D = diag(v2);
网友答案:

I don't have matlab on-hand right now, but I'd use a combination of the following functions: - diag - eye - logical

An equivalent question was answered here: How to assign values on the diagonal?

相关阅读:
Top