Finding Minimum value of an anonymous function using fminbnd

Hi,
I am trying to find the minimum value of my anonyus function G, which depends on the variable na. I am getting the error "User supplied obective function mus return a scalar value" when I try to run my code. From some debugging, I can see that if I type G(0) in the command line, I get a 1X1000 double that is just the correct value for G(na=0), but repeated 1000 times. Can anyone help me fix this? Thanks for any advice, I've never posted on here before.
clear all
% Given :
R = 1.987; %[cal/mol*K]
T = 500; %[K]
G0 = -1000; %[cal/mol]
%% Find values to plot G vs. E
% Calulate na for a bunch of E:
% E: [0,1]
E = linspace(0,1,1000); % get 1000 evenly spaced values of E between 0 and 1
na = (.5.*(1-E)); % CHANGE THIS FOR THE EQUATION IN THE PROBLEM
% Calculate G-(ua/2)-(ub/2)
A = (1-(2.*na)); % define this bc it gets used a lot below
G = @(na) ((A.*G0)+((R*T).*((2.*na.*log(na))+(A.*log(A)))));
% plot it
figure();
plot(E, G(na))
title('Free Energy of System, G');
ylabel('G [cal/mol]'); xlabel('E');
% find minimum G value (equilbrium)
[na_min, Gmin] = fminbnd(G,na(end), na(2))

 채택된 답변

Bruno Luong
Bruno Luong 2020년 9월 8일
편집: Bruno Luong 2020년 9월 8일
You should not mix between discrete sampling of your function G and continuous evaluation required by FMINBND
% Given :
R = 1.987; %[cal/mol*K]
T = 500; %[K]
G0 = -1000; %[cal/mol]
%% Find values to plot G vs. E
% Calulate na for a bunch of E:
% E: [0,1]
E = linspace(0,1,1000); % get 1000 evenly spaced values of E between 0 and 1
na = (.5.*(1-E)); % CHANGE THIS FOR THE EQUATION IN THE PROBLEM
% Calculate G-(ua/2)-(ub/2)
A = @(na) (1-(2.*na)); % define this bc it gets used a lot below
G = @(na) ((A(na).*G0)+((R*T).*((2.*na.*log(na))+(A(na).*log(A(na))))));
% find minimum G value (equilbrium)
[na_min, Gmin] = fminbnd(G,na(end), na(2))
Emin = 1 - na_min/0.5 % recover corresponding energy
figure();
plot(E, G(na),'b',Emin,Gmin,'+r')
title('Free Energy of System, G');
ylabel('G [cal/mol]'); xlabel('E');

댓글 수: 1

Hi Bruno,
Thank you for your help. That makes much more sense now, I had never encoutnered fminbnd before.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Alan Stevens
Alan Stevens 2020년 9월 8일
You don't need fminbnd to find the minimum of G. Just
min(G(na))
will do it (or am I missing something?).

카테고리

도움말 센터File Exchange에서 Mathematics에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by