简体   繁体   中英

How to plot rosenbrock function in matlab

I'm trying to plot rosenbrock function

Rosenbrock Function

like this

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

I know the above function implementation is not correct. With loop it can be easily done, but with vectorization I'm getting wrong results. Can any body help.

Rosenbrock

The vectorized version of rosenbrock function would be -

sum(100*(xx(2:end) - xx(1:end-1).^2).^2 + (xx(1:end-1)-1).^2)

Sample run -

% 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM