MATLAB: Fmincon constraints error: Aeq must have 81 column(s).

fminconlinear constraints

I am trying to minimize the norm of a matrix. But I want to put constraints on my argument x which is a 9×9 matrix such that x*ones(9,1) = ones(9,1) i.e all the rows of matrix x must sum to one
fun = @(x) norm(A*x - B);
rng(4)
x0 = rand(9,9);
lb = zeros(1,81);
ub = ones(1,81)*0.999999;
A = [];
b = [];
Aeq = ones(9,1);
beq = ones(9,1);
nonlcon = [];
options = optimoptions(@fmincon,'Algorithm','sqp','MaxFunctionEvaluations',5000)
x = fmincon(fun,x0,A,b,Aeq,beq,lb,ub,nonlcon, options);
Here A and B are two 15×9 matrices.
I get this error: Aeq must have 81 column(s).

Best Answer

See this example. This consider random values for matrices A and B in fun
rng(0);
A = rand(9);
B = rand(9);
fun = @(x) norm(A*reshape(x,9,9) - B);
rng(4)
x0 = rand(1,81);
lb = zeros(1,81);
ub = ones(1,81)*0.999999;
A = [];
b = [];
Aeq = repelem(eye(9),1,9);
beq = ones(9,1);
nonlcon = [];
options = optimoptions(@fmincon,'Algorithm','sqp','MaxFunctionEvaluations',5000);
x = fmincon(fun,x0,A,b,Aeq,beq,lb,ub,nonlcon, options);
x = reshape(x, 9, 9);