arrays - 在 Matlab 中使用匿名 fnc 时如何将值存储到数组中以绘制它们
问题描述
我在绘制迭代次数与成本函数(f_star1)时遇到问题。我无法将迭代(niter)和在每次迭代中评估的函数保存到数组中。下面是我的代码。while 循环中的注释中指定的行是我卡住的地方!
% define initial guess
x = [1 1]';
% define parameters
h = 1; % initial step size
beta = 0.7; % Armijo's Rule: Beta = (0,1)
alpha = 0.2; % Armijo's Rule: Alpha = (0,.5)
grad = 1; % initialize gradient
epsilon = 1e-2;
niter = 0; % iterations counter
f = @costf; % objective fcn assigned to variable f
i = 1;
n=0;
% Loop
while norm(grad) > epsilon
grad = gradient(x(:,end));
while f(x(:,end)-h*grad) > (f(x(:,end))-alpha*h*grad) %backtracking line search
h = h*beta;
end
x(:,end+1) = x(:,end) - h*grad;
%This is the part I am stuck!!!
x1G = x(1,:)';
x2G = x(2,:)';
x_star1 = [(x(1,:));(x(2,:))]';
f_star1(i,:) = costf(x_star1(i,:));
% figure(1), plot(iterations,f_star1,'*')
niter= niter+1;
end
% plot(f_star1,niter,'*')
%Cost Function
function f = costf(x)
f = exp(x(1)+3*x(2)-0.1) + exp(x(1)-3*x(2)-0.1) + exp(-x(1)-0.1);
end
% find gradient with central difference
function df = gradient(x0)
f = @costf; % assign cost fcn function to variable f
h_step = .01; % perturbation step
dx1 = (f(x0+[h_step;0])-f(x0-[h_step;0]))/(2*h_step); %slope
dx2 = (f(x0+[0;h_step])-f(x0-[0;h_step]))/(2*h_step);
df = [dx1;dx2];
end
解决方案
首先,要使用plot(niter, f_star1)
函数,niter
并且f_star1
在您的情况下应该是两个长度相等的向量。问题i
出在while循环中。你需要i
在迭代中增加。
% define initial guess
x = [1 1]';
% define parameters
h = 1; % initial step size
beta = 0.7; % Armijo's Rule: Beta = (0,1)
alpha = 0.2; % Armijo's Rule: Alpha = (0,.5)
grad = 1; % initialize gradient
epsilon = 1e-2;
niter = 0; % iterations counter
f = @costf; % objective fcn assigned to variable f
i = 1;
n=0;
% Loop
while norm(grad) > epsilon
grad = gradient(x(:,end));
while f(x(:,end)-h*grad) > (f(x(:,end))-alpha*h*grad) %backtracking line search
h = h*beta;
end
x(:,end+1) = x(:,end) - h*grad;
%This is the part I am stuck!!!
x1G = x(1,:)';
x2G = x(2,:)';
x_star1 = [(x(1,:));(x(2,:))]';
f_star1(i,:) = costf(x_star1(i,:));
niter(i,:)= i-1;
i = i+ 1;
end
plot(niter,f_star1,'*-')
title('f\_star1 vs niter');
xlabel('niter');
ylabel('f\_star1');
%Cost Function
function f = costf(x)
f = exp(x(1)+3*x(2)-0.1) + exp(x(1)-3*x(2)-0.1) + exp(-x(1)-0.1);
end
% find gradient with central difference
function df = gradient(x0)
f = @costf; % assign cost fcn function to variable f
h_step = .01; % perturbation step
dx1 = (f(x0+[h_step;0])-f(x0-[h_step;0]))/(2*h_step); %slope
dx2 = (f(x0+[0;h_step])-f(x0-[0;h_step]))/(2*h_step);
df = [dx1;dx2];
end
输出:
推荐阅读
- html - 如何在 HTML 中创建 3 列
- javascript - 使用 husky 对 json 文件预提交进行排序
- python - django.apps:当我在 get_models() 上循环时,模板渲染期间出现错误
- scala - spark中的静态分配如何工作?
- r - 当块包含 ggplot 图像时,render / build_site 不起作用
- java - 中断其他进程的线程
- autoit - 如何在 GUI 中显示更改的文件中的文本?
- javascript - JS 特别是从字符串更改日期格式
- excel - 如何验证工作簿中是否已存在 Excel 工作表?
- jquery - 如何在 Kendo UI 图表上包装 categoryAxis 文本