Related
I am trying to use a genetic algorithm for the first time. I am having trouble with an error.
Error using ga (line 393)
Unrecognized function or variable 'A_unfinned'.
Error in microprocessor_ga_Sanders (line 10)
[best_X,best_Objective] =
ga(#microprocessor_cost,NVARS,[],[],[],[],lb,ub,#Constraint_function_microprocessor_Sanders,INTCON,options)
Caused by:
Failure in initial user-supplied nonlinear constraint function evaluation.
I would like some help trying to assess the problem. I have been working on this for hours and cant figure it out.
clc
clear
close all
options = optimoptions('ga','Display','iter','ConstraintTolerance',0);
NVARS=3;
lb=[1, 0.0005, 0.0005];
ub=[30, 0.03, 0.03];
INTCON = [1];
[best_X,best_Objective] = ga(#microprocessor_cost,NVARS,[],[],[],[],lb,ub,#Constraint_function_microprocessor_Sanders,INTCON,options)
I will attach all of the functions I refer to in my code.
Objective function:
function [cost] = microprocessor_cost(X)
%function to determine the cost of an aluminum, rectangular heat sink
% N is the number of fins
% L is the length of the fins
% t is the thickness of fins
% b is the height of the base of the heat sink
w=0.0508; %w and r are hardcoded for the specific problem
r=0.0508;
b=0.002;
N=X(:,1);
L=X(:,2);
t=X(:,3);
volume_base=b*w*r;
volume_fins=L*w*t*N;
volume_total=volume_base+volume_fins;
cost=volume_total*849064;
end
Constraint function:
function [C, Ceq] = Constraint_function_microprocessor_Sanders(X)
%C is vector of inequality constraints. GA keeps it less than zero, i.e. C<0 and only solutions with C<0 are feasible
%Ceq is vecor of equality constraints (we have none). GA keeps it equal to zero, i.e. Ceq=0, and only solutions with Ceq=0 ARE FEASIBLE
Resistance = resistance_microprocessor(X);
%the following will make unrealistic designs infeasible
if A_unfinned<0
Resistance = 1000;
end
Target_Resistance=50/15;
C = Resistance - Target_Resistance; % C<0, implies Resistance<Target_Resistance
Ceq = [];
end
Resistance Function:
function [Resistance] = resistance_microprocessor(X)
%UNTITLED4 Summary of this function goes here
% Detailed explanation goes here
%2in by 2in microprocessor - assuming that the width and length of the heat
%sink is equal to the width and length of the microprocessor
%2in = 0.0508m
w=0.0508; %m
l=0.0508; %m 2x2 inch microprocessor
fins=X(:,1);
L=X(:,2);
t=X(:,3);
%assuming no thermal grease between microprocessor and heat sink
contact_resistance_per_area=0.001; %K/(W*m^2)
Tamb=30+273; %K
v=0.000021; %m^2/s
Pr=0.7;
k_air=0.03; %W/(m*K)
%% Design deciscions
Tambient=293; %K, ambient air temperature
b=0.002; %m, height of base of heat sink
k=240; %W/(m*K), aluminum fins
%% Calculations
%calculated, (80+30)/2 = 55, (55+80)/2 = 42.5
Tfilm=42.5+273; %K
%chosen length of fins: 75 mm, which is the maximum length, Lc for vertical
%plate = L
Lc=0.075; %m,
%solve for natural convection coefficient
h=function_get_convection_coefficient(Tfilm,Tamb,Lc,v,Pr,k_air); %W/m^2
%constraint - must be able to dissipate 15 W
q=15; %W
%thermal network calculations - thermal resistances
%contact resistance
area_transistor=w*l;
R_contact=contact_resistance_per_area*area_transistor;
%resistance - conduction through base
A_base=l*w;
R_base=b/(k*A_base);
%fin thermal resistance - convection
n=function_get_fin_efficiency(h,L,t,w,k); %fin efficiency using function
surf_area_fins=fins*2*(L*w); %ignoring the convection through the end and through top and bottom
R_fins=1/(h*surf_area_fins*n);
%unfinned thermal resistance
A_unfinned=(l-(fins*t))*w;
R_unfinned=1/(h*A_unfinned);
%overall thermal resistance of system
Resistance=R_contact+R_base+(1/(1/R_fins)+(1/R_unfinned));
end
Actually, the error output directly tells you what the problem is.
In your function Constraint_function_microprocessor_Sanders the variable A_unfinned does not exist.
To resolve this, you might want to pass it from your function resistance_microprocessor(X). This means, doing the following changes:
Change function [Resistance] = resistance_microprocessor(X) to
function [Resistance,A_unfinned] = resistance_microprocessor(X)
In function Constraint_function_microprocessor_Sanders change Resistance = resistance_microprocessor(X); to[Resistance,A_unfinned] = resistance_microprocessor(X);
If there are no other problems, this might help.
Alternative:
Another possibility to resolve this might be to move
if A_unfinned<0
Resistance = 1000;
end
to the end of the resistance_microprocessor function.
I've been trying to translate a set of chemical equations to MATLAB code, to be able to solve for different chemical species. I have the approximate solution (as it's from a graph) but after entering all the data and checking multiple times I still haven't been able to find what is wrong. I'm wondering what is going wrong and if anyone could please help me out. The source for the graph/equation is the article at this link: The chemistry of co-injected BOE. The graph I want to reproduce later on is figure 2 in the paper, see the image below:
Now the results I get for 10cc, 40cc and 90cc are respectively:
HF 43%, H2F2 48%, F- 3%, HF2- 6% in comparison ~28%, 63%, 2%, 7% (10cc).
HF 35%, H2F2 33%, F- 14%, HF2- 18% in comparison ~24%, 44%, 6%, 26% (40cc).
HF 21%, H2F2 12%, F- 37%, HF2- 30% in comparison ~18%, 23%, 20%, 45% (90cc).
The script is the following:
clc;
clear all;
%Units to be used
%Volume is in CC also cm^3, 1 litre is 1000 CC, 1 cc = 1 ml
%density is in g/cm^3
%weigth percentages are in fractions of 0 to 1
%Molecular weight is in g/mol
% pts=10; %number of points for linear spacing
%weight percentages of NH4OH and HF
xhf=0.49;
xnh3=0.28;
%H2O
Vh2o=1800;
dh2o=1.00; %0.997 at 25C when rounded 1
mh2o=18.02;
%HF values
Vhf=100;
dhf49=1.15;
dhf=dh2o+(dhf49-dh2o)*xhf/0.49; %# 25C
Mhf=20.01;
nhf=mols(Vhf,dhf,xhf,Mhf);
%NH4OH (NH3) values
% Vnh3=linspace(0.1*Vhf,1.9*Vhf,pts);
Vnh3=10;
dnh3=0.9; %for ~20-31% #~20-25C
Mnh3=17.03; %The wt% of NH4OH actually refers to the wt% of NH3 dissolved in H2O
nnh3=mols(Vnh3,dnh3,xnh3,Mnh3);
if max(nnh3)>=nhf
error(['There are more mols NH4OH,',num2str(max(nnh3)),', than mols HF,',num2str(nhf),'.'])
end
%% Calculations for species
Vt=(Vhf+Vh2o+Vnh3)/1000; %litre
A=nhf/Vt; %mol/l
B=nnh3/Vt; %mol/l
syms HF F H2F2 HF2 NH3 NH4 H OH
eq2= H*F/HF==6.85*10^(-4);
eq3= NH3*H/NH4==6.31*10^(-10);
eq4= H*OH==10^(-14);
eq5= HF2/(HF*F)==3.963;
eq6= H2F2/(HF^2)==2.7;
eq7= H+NH4==OH+F+HF2;
eq8= HF+F+2*H2F2+2*HF2==A;
eq9= NH3+NH4==B;
eqns=[eq2,eq5,eq6,eq8,eq4,eq3,eq9,eq7];
varias=[HF, F, H2F2, HF2, NH3, NH4, H, OH];
assume(HF> 0 & F>= 0 & H2F2>= 0 & HF2>= 0& NH3>= 0 & NH4>= 0 & H>= 0 & OH>= 0)
[HF, F, H2F2, HF2, NH3, NH4, H, OH]=vpasolve(eqns,varias);% [0 max([A,B])])
totalHF=double(HF)+double(F)+double(H2F2)+double(HF2);
HFf=double(HF)/totalHF %fraction of species for HF
H2F2f=double(H2F2)/totalHF %fraction of species for H2F2
Ff=double(F)/totalHF %fraction of species for F-
HF2f=double(HF2)/totalHF %fraction of species for HF2-
an extra function needed is called mols.m
%%%% amount of mol, Vol=volume, d=density, pwt=%weight, M=molecularweight
function mol=mols(Vol, d, pwt, M)
mol=(Vol*d*pwt)/M;
end
The equations being used from the article are in the image below:
(HF)2 is H2F2 in my script
So appears the issue wasn't so much with Matlab, had some help in that area as well.
Final solution and updated Matlab code can be found here:
https://chemistry.stackexchange.com/questions/98306/why-do-my-equilibrium-calculations-on-this-hf-nh4oh-buffer-system-not-match-thos
A subquestion of my assignment requires to compute the implied volatility σ via the Black and Scholes option valuation formula which is:
More specifically, it requires to solve the equation numerically via rootsolving for σ when all parameters have given values.
I am trying to use the fzero function of MATLAB in order to estimate σ. I created two scripts.
The fist script includes:
S_0 = 1403; % Stock Price
K = 1350 ; % Strike Price
rf = 0.0534; % Risk Free Rate
div=0.0118; % Divident Rate
T=0.1028; % Maturity Period
C=81;% Call option value
fixed_input=[S_0,K,rf,div,T,C];% Construct vector input values
save ('fixed_input.mat','fixed_input');
imp_vol_ini=0.1; % Initial Implied Volatility Value
BlackScholes = #BSF;
[imp_vol,y]=fzero(BlackScholes,imp_vol_ini)
While the second script includes the code:
function y=BSF(imp_vol)
load fixed_input
S_0=fixed_input(1);
K=fixed_input(2);
rf=fixed_input(3);
div=fixed_input(4);
T=fixed_input(5);
C=fixed_input(6);
d1_nominator=log(S_0/K)+(rf-div+(imp_vol^2)/2)*T;
d1_denominator=imp_vol*sqrt(T);
d1=d1_nominator/d1_denominator;
d2=d1-imp_vol*sqrt(T);
y=C-(exp(-div*T))*S_0*normcdf(d1)+K*(exp(-rf/T))*normcdf(d2);
end
The code works but the numbers are not reasonable. Normally, after the solving, y should be close to zero while σ should lie between the interval [0.1 , 0.3] but this is not the case. The numbers that I retrieve are y=81 while σ=-2.7018e-16.
I sense that this has something to do with the constraints and the options of the fzero. Can you please help me?
The error is in the last line of BSF function which is:
y=C-(exp(-div*T))*S_0*normcdf(d1)+K*(exp(-rf/T))*normcdf(d2);
% ↑
You wrote a / instead of *. It should've been this:
y=C-(exp(-div*T))*S_0*normcdf(d1)+K*(exp(-rf*T))*normcdf(d2);
% ↑
I'm trying to implement a simple SVM linear binary classification in Matlab but I got strange results.
I have two classes g={-1;1} defined by two predictors varX and varY. In fact, varY is enough to classify the dataset in two distinct classes (about varY=0.38) but I will keep varX as random variable since I will need it to other works.
Using the code bellow (adapted from MAtlab examples) I got a wrong classifier. Linear classifier should be closer to an horizontal line about varY=0.38, as we can perceive by ploting 2D points.
It is not displayed the line that should separate two classes
What am I doing wrong?
g(1:14,1)=1;
g(15:26,1)=-1;
m3(:,1)=rand(26,1); %varX
m3(:,2)=[0.4008; 0.3984; 0.4054; 0.4048; 0.4052; 0.4071; 0.4088; 0.4113; 0.4189;
0.4220; 0.4265; 0.4353; 0.4361; 0.4288; 0.3458; 0.3415; 0.3528;
0.3481; 0.3564; 0.3374; 0.3610; 0.3241; 0.3593; 0.3434; 0.3361; 0.3201]; %varY
SVMmodel_testm = fitcsvm(m3,g,'KernelFunction','Linear');
d = 0.005; % Step size of the grid
[x1Grid,x2Grid] = meshgrid(min(m3(:,1)):d:max(m3(:,1)),...
min(m3(:,2)):d:max(m3(:,2)));
xGrid = [x1Grid(:),x2Grid(:)]; % The grid
[~,scores2] = predict(SVMmodel_testm,xGrid); % The scores
figure();
h(1:2)=gscatter(m3(:,1), m3(:,2), g,'br','ox');
hold on
% Support vectors
h(3) = plot(m3(SVMmodel_testm.IsSupportVector,1),m3(SVMmodel_testm.IsSupportVector,2),'ko','MarkerSize',10);
% Decision boundary
contour(x1Grid,x2Grid,reshape(scores2(:,1),size(x1Grid)),[0 0],'k');
xlabel('varX'); ylabel('varY');
set(gca,'Color',[0.5 0.5 0.5]);
hold off
A common problem with SVM or any classification method for that matter is unnormalized data. You have one dimension that spans for 0 to 1 and the other from about 0.3 to 0.4. This causes inbalance between the features. Common practice is to somehow normalize the features, for examply by std. try this code:
g(1:14,1)=1;
g(15:26,1)=-1;
m3(:,1)=rand(26,1); %varX
m3(:,2)=[0.4008; 0.3984; 0.4054; 0.4048; 0.4052; 0.4071; 0.4088; 0.4113; 0.4189;
0.4220; 0.4265; 0.4353; 0.4361; 0.4288; 0.3458; 0.3415; 0.3528;
0.3481; 0.3564; 0.3374; 0.3610; 0.3241; 0.3593; 0.3434; 0.3361; 0.3201]; %varY
m3(:,2) = m3(:,2)./std(m3(:,2));
SVMmodel_testm = fitcsvm(m3,g,'KernelFunction','Linear');
Notice the line before the last.
I am receiving the following error message:
Attempted to access sym(67); index out of bounds because numel(sym)=2.
I have been working on this for three days. I looked for similar error, but it didn't help. My code is below:
filename='DriveCyclesCP.xlsx';
V=xlsread('DriveCyclesCP.xlsx',2,'C9:C774'); % Get the velocity values, they are in an array V.
N=length(V); % Find out how many readings
mass = 1700 ; % Vehicle mass+ two 70 kg passengers.
area_Cd = 0.75; % Frontal area in square metres
Crr=0.009; %rolling resistance
g=9.8; % gravity acceleration
T=774; %UDDS cycle time duration
V_ave = 21.5; % UDDS avearage speed im m/s
rd=0.3; % Effective tire radius
Qhv =12.22; % E85 low Heating value in kWh/kg
Vd = 2.189; % engine size in L
md=0.801; % mass density of Ethanol
mf =Vd*md; % mf is the fuel mass consumed per cycle
Per = zeros(1,N); % engine power for each point of the drive cycle
a = zeros(1,N); % acceleration
SFC = zeros(1,N); % specific fuel consumption
Wc = zeros (1,N); % mass flow rate
nf = zeros (1,N); %fuel efficiency
Pm = zeros (1,N); % motor power
Pt = zeros (1,N);
Te =zeros (1,N); % Engine Troque
Tt = zeros (1,N);
Tm =zeros (1,N);
we =zeros (1,N); % Engine rot speed
wt = zeros (1,N);
wm =zeros (1,N);
S =zeros (1,8);
int (sym ('C'));
for C=1:N
a(C)=V(C+1)-V(C);
Pt(C)= V(C)*(mass*g*Crr + (0.5*area_Cd*1.202*(V(C))^2) + mass*a(C))/1000;
Per(C)=(mass*g*Crr +0.5*area_Cd*1.202*(V(C))^2 +mass*g*0.03)/1000*0.85;% e
syms Te(C) Tt(C) Tm(C) wt(C) we(C) wm(C) k1 k2
S = solve( Pm(C)==Pt(C) - Per(C), Tt(C)*wt(C)== Pt(C), Tt(C)*wt(C)== Te(C)*we(C) + Tm(C)*wm(C), wt(C)==we(C)/k1, wt(C)==wm(C)/k2, Pm(C)==wm(C) *Tm(C), Per(C)==we(C) *Te(C), Tt == k1*Te + k2*Tm );
end
The problem is on the line
int (sym ('C'));
You have defined sym to be a matrix with 2 entries somewhere (either earlier in the code or in a previous mfile), thus it treats sym as a matrix instead of a function. Thus when Matlab gets to the statement sym('C') it first converts the character 'C' to its ASCII integer representation (this just happens to be the number 67), then it tries to calculate sym(67) which is impossible as sym only has 2 elements.
Thus you have to stop sym from being a matrix (variable) and let it be a function again. There are two ways to solve this, either you can start you file with the statement clear;, this will remove all variables in memory, which might not be what you want; or you can use a function instead of script, as this hides all variables that have been defined previously and prevents this sort of error.
Note the line numel(X) is a way to measure how many elements are in X. Thus numel(sym)=2 means that sym has 2 elements.
P.S. There is an error in the lines (notice that I only taken some of the lines of you code)
N=length(V); % Find out how many readings
for C=1:N
a(C)=V(C+1)-V(C);
end
When C becomes equal to N, then V(C+1) will generate an error.