Solve problem of choice of resistor
2 views (last 30 days)
Sergey Kostrukov on 19 Nov 2021
I'm trying to learn the Optimization Toolkit by trying solve a very simple optimization problem:
I have a a simple LED circuit consisting of three elements: a power source, LED and resistor.
Each element has own operational constraints. I want to choose a resistor from a list of available resistors, which provides highest current to LED while fitting into the constraints.
% Power source
source_V = 5 % voltage of the power source
source_I_max = 0.04 % max current draw from the power source
resistor_R = [100 220 330 1000 10000 100000 1000000] % available resistors
led_V_forward = 1.85 % forward volage of the LED
led_I_max = 0.02 % max current for the LED
% Find resistor_idx, index of the desired resistor from the list resistor_R
% integer, discrete
resistor_idx = optimvar('resistor_idx')
% LED current, optimization variable which we need to iterate
% real number
% we need max value
led_I = optimvar('led_I')
led_I = (source_V - led_V_forward) / resistor_R(resistor_idx)
led_I <= source_I_max % LED should draw current below limitation of the power source
led_I <= led_I_max % LED should draw current below own limiation
resistor_idx % is discrete variable, index of resistor_R value
Please help me define this problem in MATLAB. I'm getting confused what is my objective (resistor_idx or led_I) and how to defined discrete constraint of resistor_idx and what kind of optimization should I use.
Alan Weiss on 21 Nov 2021
To allow this code to work, I copy over your data.
% Power source
source_V = 5; % voltage of the power source
source_I_max = 0.04; % max current draw from the power source
resistor_R = [100 220 330 1000 10000 100000 1000000]; % available resistors
led_V_forward = 1.85; % forward volage of the LED
led_I_max = 0.02; % max current for the LED
I think that you need to be more careful in defining your optimization variable:
resistor_idx = optimvar('resistor_idx',"Type","integer","LowerBound",1,"UpperBound",7);
Also, I don't think that led_I is an optimization variable. So remove the line
% led_I = optimvar('led_I') % Remove this line
You need to create an optimization problem for maximization.
prob = optimproblem("ObjectiveSense","max");
You need to use fcn2optimexpr to create your objective, because you cannot use an optimization variable as an index.
fun = fcn2optimexpr(@(x)(source_V - led_V_forward) /resistor_R(x),resistor_idx);
prob.Objective = fun;
Put the constraints in the problem.
prob.Constraints.led = fun <= source_I_max; % LED should draw current below limitation of the power source
prob.Constraints.led2 = fun <= led_I_max;
Solve the problem like this:
[sol,fval] = solve(prob)
You see that integer-constrained problems are not so simple to set up. But you can do it if you are careful to follow the limitations.
MATLAB mathematical toolbox documentation