Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/matlab/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在matlab中绘制rosenbrock函数_Matlab_Function_Plot - Fatal编程技术网

如何在matlab中绘制rosenbrock函数

如何在matlab中绘制rosenbrock函数,matlab,function,plot,Matlab,Function,Plot,我正在尝试绘制rosenbrock函数的 像这样 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),...

我正在尝试绘制rosenbrock函数的

像这样

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
我知道上面的函数实现是不正确的。使用循环可以很容易地完成,但是使用矢量化我得到了错误的结果。有人能帮忙吗

的矢量化版本将是-

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
的矢量化版本将是-

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

使用您的代码,我在调用重塑函数时遇到此错误<代码>要重塑元素的数量,必须保持不变。
@KarenJohnson好吧,我没有使用
重塑
。因此,我不确定您是如何使用我的代码的。另外,我假设函数输出标量,就像loopy实现一样。@KarenJohnson链接的loopy代码是否适用于您的情况?为什么不共享为您工作的循环代码,然后我们可以将其矢量化?我正在使用我上面的代码。我刚刚更改了rosenbrock函数@KarenJohnson,但您在问题中说您的代码不正确。您是否有正确/有效的循环实现?如果有,可以和大家分享一下吗?在代码中,我在调用重塑函数时遇到了这个错误<代码>要重塑元素的数量,必须保持不变。@KarenJohnson好吧,我没有使用
重塑
。因此,我不确定您是如何使用我的代码的。另外,我假设函数输出标量,就像loopy实现一样。@KarenJohnson链接的loopy代码是否适用于您的情况?为什么不共享为您工作的循环代码,然后我们可以将其矢量化?我正在使用我上面的代码。我刚刚更改了rosenbrock函数@KarenJohnson,但您在问题中说您的代码不正确。您是否有正确/有效的循环实现?如果有,你能分享一下吗?