MATLAB Answers

Trying to find a minimum value

조회 수: 1(최근 30일)
Surya Ramanthan
Surya Ramanthan 2020년 11월 20일
편집: Jon 2020년 11월 20일
In this code, I am trying to find the minimum value of rho_Tw, and find the associated w value with it (so basically trying to find the x value associated with the minimum y value). However, whenever I run the following code, I get 0. Any corrections would be greatly appreciated.
AA = [2 0 -2 0 0 0 0 0 0 0;
0 2 0 -2 0 0 0 0 0 0;
0 -1 7 -2 -3 0 0 0 0 0;
0 0 0 1 -1 0 0 0 0 0;
0 0 0 0 4 0 0 -2 0 0;
0 0 0 0 0 1 0 0 0 -1;
-2 0 0 0 0 0 2 0 0 0;
0 0 -4 0 0 -1 0 8 -3 0;
0 0 0 0 0 -2 0 0 7 -4;
0 0 0 0 0 0 -3 0 0 4];
L = -tril(AA, -1);
U = -triu(AA, 1);
D = diag(AA);
DD = diag(D);
Tj=inv(DD)*(L+U);
rho_Tj=max(abs(eig(Tj)));
for w = 0:0.0005:2
wb=0;
rho_min=0;
Tw=inv(DD-w*L)*(((1-w)*DD)+(w*U));
rho_Tw=max(abs(eig(Tw)))
scatter(w, rho_Tw)
hold on
if w == 0
rho_min = rho_Tw;
wb = w;
end
if rho_Tw < rho_min
rho_min = rho_Tw;
wb=w;
end
end
disp(wb)

채택된 답변

Jon
Jon 2020년 11월 20일
편집: Jon 2020년 11월 20일
You may have some additional problems but one is that you reset wb to zero with every loop iteration, first line in your loop is
wb=0
So although wb get set to the minimum value in your if statement, it immediately gets wiped out in the next loop iteration
I would suggest that rather than finding the minimum yourself with the if statements you just caculate a vector of rho_Tw values and then use MATLAB's min function like this
AA = [2 0 -2 0 0 0 0 0 0 0;
0 2 0 -2 0 0 0 0 0 0;
0 -1 7 -2 -3 0 0 0 0 0;
0 0 0 1 -1 0 0 0 0 0;
0 0 0 0 4 0 0 -2 0 0;
0 0 0 0 0 1 0 0 0 -1;
-2 0 0 0 0 0 2 0 0 0;
0 0 -4 0 0 -1 0 8 -3 0;
0 0 0 0 0 -2 0 0 7 -4;
0 0 0 0 0 0 -3 0 0 4];
L = -tril(AA, -1);
U = -triu(AA, 1);
D = diag(AA);
DD = diag(D);
Tj=inv(DD)*(L+U);
rho_Tj=max(abs(eig(Tj)));
% assign w vector
w = 0:0.0005:2;
% preallocate array to hold rho_Tw values
rho_Tw = zeros(length(w),1);
% loop to evaluate rho_Tw as a function of w
for k = 1:length(w)
Tw=inv(DD-w(k)*L)*(((1-w(k))*DD)+(w(k)*U));
rho_Tw(k) =max(abs(eig(Tw)));
end
% find minimum
[rho_min,idxMin] = min(rho_Tw);
wb = w(idxMin);
% plot results
scatter(w,rho_Tw)
% display results
disp(rho_min)
disp(wb)

추가 답변(0개)

Community Treasure Hunt

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

Start Hunting!

Translated by