Implementation of grid search for a function

27 visualizaciones (últimos 30 días)
Sardor Butunboev
Sardor Butunboev el 5 de Oct. de 2021
Respondida: Deepak el 9 de Sept. de 2024
I am trying to run a grid search and find x*. but it gives me "Not enough input arguments".
funktion = @(x) sqrt(x) + 2*sqrt(1-x);
x = [0:0.001:1];
x_star_grid = grid(funktion, x)
function [f_benchmark, domain_max] = grid(funktion, domains)
domain_max = -1e+5;
for i = 1:length(domains)
z= domains(i);
disp(z)
f = feval(funktion, z);
if f>=f_benchmark
f_benchmark = f;
domain_max = domains(i);
end
end
end

Respuestas (1)

Deepak
Deepak el 9 de Sept. de 2024
To my understanding, you have written a “grid” function in MATLAB to find maximum value of a given function within a specified domain. However, on calling the function the compiler throws the following error: “Not enough input arguments”.
On investigating the code, I found that the error occurs due to incorrect number of output arguments on “grid” function call. The output arguments while calling the function should match the function definition.
Please find below the correct function call to “grid”:
[x_star_grid, f_benchmark] = grid(funktion, x);
Additionally, the variable “f_benchmark” should be initialized with some default value, before using it inside the “if” statement to avoid the “unrecognized variable” error.
f_benchmark = -Inf; % Initialize f_benchmark to a very low value
Below is the complete MATLAB code with all the required changes:
funktion = @(x) sqrt(x) + 2*sqrt(1-x);
x = 0:0.001:1;
[x_star_grid, f_benchmark] = grid(funktion, x);
function [f_benchmark, domain_max] = grid(funktion, domains)
domain_max = -1e+5;
f_benchmark = -Inf; % Initialize f_benchmark to a very low value
for i = 1:length(domains)
z = domains(i);
f = feval(funktion, z);
if f >= f_benchmark
f_benchmark = f;
domain_max = domains(i);
end
end
end
Attaching the documentation of “functions” in MATLAB for reference:
I hope this resolves the issue.

Categorías

Más información sobre App Building en Help Center y File Exchange.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by