fminbnd not working for storing values in array.
조회 수: 2 (최근 30일)
이전 댓글 표시
I keep getting this error.
Error in ScratchWork (line 12)
[Vmin(i),DragMin(i)] = fminbnd(Drag,0,15000);
I don't know what wrong.
this is the code
s = 0.6;
W = linspace(12000,20000,100);
%array of W values given
Drag = @(V) (0.01*s*V^2) + (0.95/s).*((W./V)^2);
Vmin = zeros(1,length(W));
DragMin = zeros(1,length(W));
for i = 1:1:length(W) %incrementing for loop by 1 to the length of array W
[Vmin(i),DragMin(i)] = fminbnd(Drag,0,15000);
%calling fminbnd function for each new W value to store in each V and D with respect to ii
end
hold on
grid on
plot(W, Vmin, 'r', W, DragMin, 'g');
legend('Minimum Velocity', 'Minimum Drag');
xlabel('Weight(W)');
title('Sensitivity Analysis');
댓글 수: 0
답변 (2개)
Walter Roberson
2019년 1월 31일
Your W is a vector, so in
Drag = @(V) (0.01*s*V^2) + (0.95/s).*((W./V)^2);
then you are calculating a vector, but fmincon needs to a scalar.
for i = 1:1:length(W) %incrementing for loop by 1 to the length of array W
Drag = @(V) (0.01*s*V^2) + (0.95/s).*((W(i)./V)^2);
[Vmin(i),DragMin(i)] = fminbnd(Drag,0,15000);
%calling fminbnd function for each new W value to store in each V and D with respect to ii
end
Star Strider
2019년 1월 31일
There are two errors.
The first is with respect to your needing to vectorise your ‘Drag’ function, and this will work:
Drag = @(V) (0.01*s*V.^2) + (0.95/s).*((W./V).^2);
and the second is that ‘Drag’ must return a scalar value, and this will work for that:
[Vmin(i),DragMin(i)] = fminbnd(@(V)norm(Drag(V)),0,15000);
Although I strongly suspect that what you intend is to define ‘Drag’ as:
Drag = @(V,W) (0.01*s*V.^2) + (0.95/s).*((W./V).^2);
and then optimise it in the loop as:
[Vmin(i),DragMin(i)] = fminbnd(@(V)Drag(V,W(i)),0,15000);
This does not require that you re-define ‘Drag’ in every iteration of your loop. Just call it with the new value of ‘W(i)’ instead. This is likely much more efficient.
댓글 수: 1
Walter Roberson
2019년 1월 31일
편집: Walter Roberson
2019년 1월 31일
You do not need to vectorize Drag. For fminbnd
fun is a function that accepts a real scalar x and returns a real scalar f
Redefining Drag each iteration is more efficient, as then fminbnd is only calling through one anonymous function instead of two (Drag and the wrapping anonymous function.)
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!