fsolve in codegen returns indexing error

N
Nicholas · Dec 7, 2020 · 1.9K views
Question
I am struggling with the code generation of a function containing the fsolve command (supported since R2020b). Since it is a rather new topic, I did not find any related entries. This is the function i try to generate the mex-file for:   function [x] = test_function(a,b) %#codegen x = zeros(1); opts = optimoptions('fsolve','Algorithm','levenberg-marquardt','Display','off'); % opts = optimoptions(opts,a.string,a.val); fcn = @(in)feval(b,in); rng default x0 = double(0.00);x(1) = fsolve(fcn,x0,opts); end And this is how I setup the code generation: cfg = coder.config('mex'); types = coder.getArgTypes('mytest','test_function') codegen -config cfg -args types test_function With the following function to get the coder.Types: function out = mytest a.val = 10e-5; a.string = "FunctionTolerance"; b = 'myeq'; out = test_function(a,b); end The struct a has no purpose yet, but will later be used to setup the optimoptions.   Error Message after calling the codegen: "??? Index expression out of bounds. Attempted to access element 1. The valid range is 1-0." In the Coder Report Viewer it sais, that the error occured in function projectBox. I would appreciate any thoughts on this.
Expert Answer
Profile picture of Prashant Kumar
Prashant Kumar PhD Expert
Answered Sep 16, 2026






Fixing fsolve Indexing Errors in MATLAB Coder


When compiling fsolve with MATLAB Coder, indexing errors occur when array sizes, vector dimensions (row vs. column), or objective function outputs lack fixed, static definitions at compile time.

Root Causes



  • Row vs. Column mismatch: x0 is a row vector (e.g., [1, 2]), but the objective function returns a column vector (e.g., [F1; F2]).

  • Dynamic output allocation: The objective function does not explicitly preallocate output arrays with static dimensions.

  • Unsupported algorithm selection: Code generation only supports specific algorithms like 'trust-region-dogleg' and 'levenberg-marquardt'.

The 4-Step Solution

1. Enforce Column Vectors Everywhere


Ensure both the initial guess x0 and the objective function output F are strictly column vectors (N-by-1).

% Correct: Column vector
x0 = [1.0; 2.0];

% Avoid: Row vector
% x0 = [1.0, 2.0];

2. Preallocate the Objective Function Output


Inside the nonlinear system function, preallocate F explicitly with zeros(N, 1) before assigning values by index.

function F = myObjective(x)
%#codegen
% Fixed size preallocation for 2 equations
F = zeros(2, 1);

F(1) = 2*x(1) - x(2) - exp(-x(1));
F(2) = -x(1) + 2*x(2) - exp(-x(2));
end

3. Configure Coder-Compatible Options


Set solver options specifically for code generation. Disable plotting and graphical outputs.

opts = optimoptions('fsolve', ...
    'Algorithm', 'trust-region-dogleg', ...
    'Display', 'off');

Complete Coder-Ready Example


Save the following solver wrapper in a file named solve_system.m:

function x_sol = solve_system(x0_init)
%#codegen

% 1. Enforce static size and column shape
coder.varsize('x0_init', [2, 1], [0, 0]); % Fixed 2x1 vector
x0 = x0_init(:); % Guarantee column vector

% 2. Set code-gen compatible options
opts = optimoptions('fsolve', ...
    'Algorithm', 'trust-region-dogleg', ...
    'Display', 'off');

% 3. Call fsolve
x_sol = fsolve(@myObjective, x0, opts);
end

function F = myObjective(x)
% Fixed-size column output
F = zeros(2, 1);
F(1) = 3*x(1) + x(2) - 5;
F(2) = x(1)^2 + x(2)^2 - 9;
end

Generate C Code (or MEX)


Test the MEX compilation in MATLAB to confirm the indexing error is resolved:

% Compile to MEX
codegen solve_system -args {zeros(2,1)}

% Run MEX
x_sol = solve_system_mex([1.0; 2.0]);
disp('Solution:');
disp(x_sol);


Summary Checklist:

  • Add %#codegen directive at the top of the function.

  • Make initial guess x0 a column vector of fixed size.

  • Preallocate F = zeros(N, 1) in the objective function.

  • Do not use anonymous functions that capture global workspace variables; pass constants directly or through arguments.





100% Run Guarantee 3-Hour Fast-Track Delivery

Need a Custom Version or Complete Simulation for This Problem?

Our 500+ PhD engineers build, debug, and optimize working MATLAB scripts and Simulink (.slx) models tailored to your exact assignment rubrics with zero plagiarism.

Tested on MATLAB R2024b / R2026a
Turnitin 0% Plagiarism Report
Free 7-Day Revisions Guarantee
Have a different question? Ask here

Get a Free Consultation or a Sample Assignment Review!