Esta página aún no se ha traducido para esta versión. Puede ver la versión más reciente de esta página en inglés.
showproblem
writeproblem
Después de crear un problema de optimización, puede revisar su formulación mediante.showproblem
Para problemas grandes, utilice en su lugar.writeproblem
Por ejemplo,
prob = optimproblem; x = optimvar('x',2,'LowerBound',0); prob.Objective = x(1) - 2*x(2); prob.Constraints.cons1 = x(1) + 2*x(2) <= 4; prob.Constraints.cons2 = -x(1) + x(2) <= 1; showproblem(prob)
OptimizationProblem : minimize : x(1) - 2*x(2) subject to cons1: x(1) + 2*x(2) <= 4 subject to cons2: -x(1) + x(2) <= 1 variable bounds: 0 <= x(1) 0 <= x(2)
Esta revisión muestra los elementos básicos del problema, como si el problema es minimizar o maximizar, y los límites de la variable. La revisión muestra los nombres de índice, si los hay, que se utilizan en las variables. La revisión no muestra si las variables son de valor entero.
Para intentar mejorar una solución o velocidad de solución, examine y cambie el solucionador predeterminado u opciones.
Para ver el solucionador y las opciones predeterminadas, utilice.optimoptions(prob)
Por ejemplo,
rng default x = optimvar('x',3,'LowerBound',0); expr = sum((rand(3,1).*x).^2); prob = optimproblem('Objective',expr); prob.Constraints.lincon = sum(sum(randn(size(x)).*x)) <= randn; options = optimoptions(prob)
options = lsqlin options: Options used by current Algorithm ('interior-point'): (Other available algorithms: 'trust-region-reflective') Set properties: No options set. Default properties: Algorithm: 'interior-point' ConstraintTolerance: 1.0000e-08 Display: 'final' LinearSolver: 'auto' MaxIterations: 200 OptimalityTolerance: 1.0000e-08 StepTolerance: 1.0000e-12 Show options not used by current Algorithm ('interior-point')
El solucionador predeterminado para este problema es, y puede ver las opciones predeterminadas.lsqlin
Para cambiar el solucionador, establezca el par nombre-valor.'Solver'
solve
Para ver las opciones aplicables para un solucionador diferente, utilice esta opción para pasar las opciones actuales al solucionador diferente.optimoptions
Por ejemplo, continuando con el problema,
options = optimoptions('quadprog',options)
options = quadprog options: Options used by current Algorithm ('interior-point-convex'): (Other available algorithms: 'trust-region-reflective') Set properties: ConstraintTolerance: 1.0000e-08 MaxIterations: 200 OptimalityTolerance: 1.0000e-08 StepTolerance: 1.0000e-12 Default properties: Algorithm: 'interior-point-convex' Display: 'final' LinearSolver: 'auto' Show options not used by current Algorithm ('interior-point-convex')
Para cambiar las opciones, use o notación de puntos para establecer opciones y pase las opciones al par nombre-valor.optimoptions
solve
'Options'
Continuando con el ejemplo,
options.Display = 'iter'; sol = solve(prob,'Options',options,'Solver','quadprog');
Iter Fval Primal Infeas Dual Infeas Complementarity 0 1.500359e+00 3.068423e-01 2.275437e+00 2.500000e-01 1 1.728717e-01 0.000000e+00 7.719860e-03 3.637874e-02 2 2.604108e-02 0.000000e+00 0.000000e+00 5.245260e-03 3 7.822161e-03 0.000000e+00 2.775558e-17 1.407915e-03 4 2.909218e-03 0.000000e+00 6.938894e-18 2.070784e-04 5 1.931264e-03 0.000000e+00 1.734723e-18 2.907724e-05 6 1.797508e-03 0.000000e+00 2.602085e-18 4.083167e-06 7 1.775398e-03 0.000000e+00 4.336809e-19 5.102453e-07 8 1.772971e-03 0.000000e+00 2.632684e-19 3.064243e-08 9 1.772848e-03 0.000000e+00 5.228973e-19 4.371356e-11 Minimum found that satisfies the constraints. Optimization completed because the objective function is non-decreasing in feasible directions, to within the value of the optimality tolerance, and constraints are satisfied to within the value of the constraint tolerance.
Para comprobar que su problema es correcto, revise todos sus aspectos. Por ejemplo, cree un problema de optimización para resolver un problema de Sudoku ejecutando este script.
x = optimvar('x',9,9,9,'LowerBound',0,'UpperBound',1); cons1 = sum(x,1) == 1; cons2 = sum(x,2) == 1; cons3 = sum(x,3) == 1; prob = optimproblem; prob.Constraints.cons1 = cons1; prob.Constraints.cons2 = cons2; prob.Constraints.cons3 = cons3; mul = ones(1,1,9); mul = cumsum(mul,3); prob.Objective = sum(sum(sum(x,1),2).*mul); cons4 = optimconstr(3,3,9); for u = 1:3 for v = 1:3 arr = x(3*(u-1)+1:3*(u-1)+3,3*(v-1)+1:3*(v-1)+3,:); cons4(u,v,:) = sum(sum(arr,1),2) <= ones(1,1,9); end end prob.Constraints.cons4 = cons4; B = [1,2,2; 1,5,3; 1,8,4; 2,1,6; 2,9,3; 3,3,4; 3,7,5; 4,4,8; 4,6,6; 5,1,8; 5,5,1; 5,9,6; 6,4,7; 6,6,5; 7,3,7; 7,7,6; 8,1,4; 8,9,8; 9,2,3; 9,5,4; 9,8,2]; for u = 1:size(B,1) x.LowerBound(B(u,1),B(u,1),B(u,1)) = 1; end
Este script tiene algunos errores que puede encontrar examinando las variables, el objetivo y las restricciones. Primero, examine la variable.x
x
x = 9×9×9 OptimizationVariable array with properties: Array-wide properties: Name: 'x' Type: 'continuous' IndexNames: {{} {} {}} Elementwise properties: LowerBound: [9×9×9 double] UpperBound: [9×9×9 double] See variables with showvar. See bounds with showbounds.
Esta pantalla muestra que el tipo de la variable es continuo. La variable debe ser de valor entero. Cambie el tipo.
x.Type = 'integer'
x = 9×9×9 OptimizationVariable array with properties: Array-wide properties: Name: 'x' Type: 'integer' IndexNames: {{} {} {}} Elementwise properties: LowerBound: [9×9×9 double] UpperBound: [9×9×9 double] See variables with showvar. See bounds with showbounds.
Revisa los límites. Debe haber 21 límites inferiores con el valor 1, uno para cada fila de.B
Dado que es una matriz grande, escriba los límites en un archivo en lugar de mostrarlos en la línea de comandos.x
writebounds(x,'xbounds.txt')
Busque en el archivo todas las instancias de.xbounds.txt
1 <=
Sólo nueve límites inferiores tienen el valor 1, en las variables,,...,.x(1,1,1)
x(2,2,2)
x(9,9,9)
Para investigar esta discrepancia, examine el código en el que establece los límites inferiores:
for u = 1:size(B,1) x.LowerBound(B(u,1),B(u,1),B(u,1)) = 1; end
La línea dentro del bucle debe decir.x.LowerBound(B(u,1),B(u,2),B(u,3)) = 1;
Restablezca todos los límites inferiores a cero y, a continuación, ejecute el código corregido.
x.LowerBound = 0; for u = 1:size(B,1) x.LowerBound(B(u,1),B(u,2),B(u,3)) = 1; end writebounds(x,'xbounds.txt')
ahora tiene el número correcto de entradas de límite inferior que son 1.xbounds.txt
Examine la función objetiva. La expresión de función objetiva es grande, así que escriba la expresión en un archivo.
writeexpr(prob.Objective,'objectivedescription.txt')
x(1, 1, 1) + x(2, 1, 1) + x(3, 1, 1) + x(4, 1, 1) + x(5, 1, 1) + x(6, 1, 1) + x(7, 1, 1) + x(8, 1, 1) + x(9, 1, 1) + x(1, 2, 1) + x(2, 2, 1) + x(3, 2, 1) + x(4, 2, 1) + x(5, 2, 1) + x(6, 2, ... 9*x(7, 8, 9) + 9*x(8, 8, 9) + 9*x(9, 8, 9) + 9*x(1, 9, 9) + 9*x(2, 9, 9) + 9*x(3, 9, 9) + 9*x(4, 9, 9) + 9*x(5, 9, 9) + 9*x(6, 9, 9) + 9*x(7, 9, 9) + 9*x(8, 9, 9) + 9*x(9, 9, 9)
La función objetiva parece razonable, porque es una suma de expresiones escalares.
Escriba las restricciones en los archivos para examinarlas.
writeconstr(prob.Constraints.cons1,'cons1.txt') writeconstr(prob.Constraints.cons2,'cons2.txt') writeconstr(prob.Constraints.cons3,'cons3.txt') writeconstr(prob.Constraints.cons4,'cons4.txt')
Revisa y verás un error.cons4.txt
Todas las restricciones son desigualdades en lugar de ecualidades. Corrija las líneas de código que crean esta restricción y coloque la restricción corregida en el problema.
cons4 = optimconstr(3,3,9); for u = 1:3 for v = 1:3 arr = x(3*(u-1)+1:3*(u-1)+3,3*(v-1)+1:3*(v-1)+3,:); cons4(u,v,:) = sum(sum(arr,1),2) == ones(1,1,9); end end prob.Constraints.cons4 = cons4;
Después de estos cambios, puede resolver el problema con éxito.
sol = solve(prob); x = round(sol.x); y = ones(size(x)); for k = 2:9 y(:,:,k) = k; % multiplier for each depth k end S = x.*y; % multiply each entry by its depth S = sum(S,3); % S is 9-by-9 and holds the solved puzzle drawSudoku(S)
Si vuelve a crear una variable, pero ya tiene una expresión que utiliza la variable antigua, puede obtener errores al incorporar las expresiones en un único problema. Ver.Las variables con nombres duplicados no permitidos
OptimizationConstraint
| OptimizationExpression
| OptimizationProblem
| OptimizationVariable
| showbounds
| showconstr
| showexpr
| showproblem
| showvar
| writebounds
| writeconstr
| writeexpr
| writeproblem
| writevar