create an fsolve loop on multiple independent variable to create a graph in matlab

Here is the general structure of how you could create a loop that will allow you to plot your function using fsolve with multiple independent variables -

main.m
% define your function with independent variables (x,y,z)
f = @(x) your_function(x(1),x(2),x(3));

% starting points for independent variables, x,y,z
x0 = [x_val,y_val,z_val];

% bounds for each independent variable (optional)
lb = [x_val_min,y_val_min,z_val_min];
ub = [x_val_max,y_val_max,z_val_max];

% Use fsolve options
options_fsolve = optimoptions('fsolve','Display','off');

for i = 1:numel(x_val_range)
    for j = 1:numel(y_val_range)
        for k = 1:numel(z_val_range)
            % create initial starting point
            x0 = [x_val_range(i),y_val_range(j),z_val_range(k)];
            
            % run FSOLVE on function, using specified options and bounds
            [x_star,fval,exitflag] = fsolve(f,x0,options_fsolve);
            
            % save results
            x_result(i,j,k) = x_star(1);
            y_result(i,j,k) = x_star(2);
            z_result(i,j,k) = x_star(3);
            
            % check if converged
            if exitflag <=0
                fprintf('Diverged for initial point, [%f, %f, %f].\n', x0(1),x0(2),x0(3));
            end
        end
    end
end

% now you can create a 3D plot using the resulting matrices
surf(x_result, y_result, z_result)
1207 chars
38 lines

Note: You will need to specify the ranges for the independent variables (x_val_range, y_val_range, z_val_range) and the initial values for starting the function (x_val, y_val, z_val). These values will depend on your specific function!

One way to choose values for the ranges is using linspace - this will create equally spaced values between a range that you specify. For example, x_val_range = linspace(0,10,100), will create a vector of 100 values between 0 and 10.

Also note that it's a good idea to specify bounds for each independent variable using lb and ub, so that fsolve doesn't go outside of the desired search space.

related categories

gistlibby LogSnag