我正在尝试绘制rosenbrock function
clear; clc; close all;
% Parameters
nx = 2; % No. of Input variables
f = @rosenbrock;
limits = repmat([-10 10], nx, 1);
titl = 'Rosenbrock';
% Plot
[X,Y] = meshgrid(linspace(limits(1,1),limits(1,2),100),...
linspace(limits(2,1),limits(2,2),100));
Z = reshape(f([X(:)'; Y(:)']), 100, 100);
surfc(X,Y,Z);
rosenbrock.m
function [y] = rosenbrock(x)
xn = circshift(x',1)';
xn(1) = 0;
y = sum(100*(xn - x.^2).^2 + (x - 1).^2);
end
我知道上面的函数实现不正确。使用循环可以很容易地完成,但是使用矢量化我得到了错误的结果。任何身体都可以帮助。
答案 0 :(得分:0)
rosenbrock function
的矢量化版本为 -
sum(100*(xx(2:end) - xx(1:end-1).^2).^2 + (xx(1:end-1)-1).^2)
示例运行 -
% Input array
>> xx
xx =
5 1 3 9 2 8 5 9 1 4
% Loopy implementation
>> d = length(xx);
sum1 = 0;
for ii = 1:(d-1)
xi = xx(ii);
xnext = xx(ii+1);
new = 100*(xnext-xi^2)^2 + (xi-1)^2;
sum1 = sum1 + new;
end
y = sum1;
>> y
y =
1698514
% Vectorized implementation
>> sum(100*(xx(2:end) - xx(1:end-1).^2).^2 + (xx(1:end-1)-1).^2)
ans =
1698514