# varindex

## 说明

idx = varindex(prob) 以结构体或整数向量形式返回问题变量的线性索引。如果您使用 prob2structprob 转换为问题结构体，则 idx 将在生成的问题结构体中给出变量索引，这些索引对应于 prob 中的变量。

idx = varindex(prob,varname) 返回 varname 的元素的线性索引。

## 示例

x = optimvar('x',3);
y = optimvar('y',3,3);
prob = optimproblem('Objective',x'*y*x);

problem = prob2struct(prob);

idx = varindex(prob);
disp(idx.x)
1     2     3
disp(idx.y)
4     5     6     7     8     9    10    11    12

idxy = varindex(prob,'y')
idxy = 1×9

4     5     6     7     8     9    10    11    12

x = optimvar('x',3,1,'LowerBound',1,'UpperBound',1);
y = optimvar('y',3,3,'LowerBound',-1,'UpperBound',1);
prob = optimproblem('Objective',x'*y*x + [2 3 4]*x);
rng default
x0.x = rand(3, 1);
x0.y = rand(3, 3);
[solp,fvalp,exitflagp,outputp] = solve(prob,x0);
Solving problem using fmincon.

Local 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.

solverprob = prob2struct(prob,x0);

[sols,fvals,exitflags,outputs] = fmincon(solverprob);
Local 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.

idx = varindex(prob);
sol.x = sols(idx.x);
sol.y = sols(idx.y);

y 使用的 varindex 索引是线性索引。将变量 sol.y 重构为大小为 x0.y

sol.y = reshape(sol.y,size(x0.y));

isequal(sol,solp)
ans = logical
1

## 输出参量

• 当您调用 idx = varindex(prob) 时，返回的 idx 是结构体。该结构体的字段名称是 prob 中的变量名称。每个字段的值是关联的基于求解器的问题变量中的变量映射到的线性索引的整数向量。

• 当您调用 idx = varindex(prob,varname) 时，返回的 idx 是关联的基于求解器的问题变量中的变量 varname 映射到的线性索引的向量。