I am receiving an error message that there are not enough input arguments in my function f.

2 Ansichten (letzte 30 Tage)
function [f, g] = rosenbrock(x)
f = sum((1 - x(1:end-1)).^2 + 100*(x(2:end) - x(1:end-1).^2).^2);
g = zeros(size(x));
g(1) = -400*x(1)*(x(2) - x(1)^2) - 2*(1 - x(1));
g(2:end-1) = 200*(x(2:end-1) - x(1:end-2).^2) - 400*x(2:end-1).*(x(3:end) - x(2:end-1).^2) - 2*(1 - x(2:end-1));
g(end) = 200*(x(end) - x(end-1)^2);
end
function [f, g] = exponential(x)
f = -exp(-0.5*sum(x.^2));
g = -x.*exp(-0.5*sum(x.^2));
end

Antworten (2)

Walter Roberson
Walter Roberson am 6 Mär. 2023
Looks to me as if it works
format long g
x = randn(1,10)
x = 1×10
-0.371911875404682 -0.313989043713682 -0.281367533926339 0.280508079780121 1.02217448547427 -0.544894220859205 -1.47050086682099 -0.617560248626988 -0.196573116936724 -0.0818487640582806
[f1, g1] = rosenbrock(x)
f1 =
1519.03045345865
g1 = 1×10
1.0e+00 * -70.0312340180861 -140.810365957436 -55.8938060907731 -67.0334996273034 838.736870722702 -706.257492462287 -1993.58070016789 -701.990241527909 -127.457920387497 -24.0979508720999
[f2, g2] = exponential(x)
f2 =
-0.11500242683972
g2 = 1×10
0.0427707682420501 0.0361095020281565 0.0323579492354364 -0.0322591099228638 -0.117552546483183 0.0626641577697472 0.169111168354326 0.0710209273118448 0.0226063854991714 0.00941280650053396
function [f, g] = rosenbrock(x)
f = sum((1 - x(1:end-1)).^2 + 100*(x(2:end) - x(1:end-1).^2).^2);
g = zeros(size(x));
g(1) = -400*x(1)*(x(2) - x(1)^2) - 2*(1 - x(1));
g(2:end-1) = 200*(x(2:end-1) - x(1:end-2).^2) - 400*x(2:end-1).*(x(3:end) - x(2:end-1).^2) - 2*(1 - x(2:end-1));
g(end) = 200*(x(end) - x(end-1)^2);
end
function [f, g] = exponential(x)
f = -exp(-0.5*sum(x.^2));
g = -x.*exp(-0.5*sum(x.^2));
end

Image Analyst
Image Analyst am 7 Mär. 2023
You're probably just clicking the green run triangle button. Doing that does not "invent" some x to pass in to the function. You have to define x somehow and then call your rosenbrock function from the command line or a script, like
x = rand(1,10);
[f, g] = rosenbrock(x);

Community Treasure Hunt

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

Start Hunting!

Translated by