Matlab - 寻找缩放曲线的解决方案

时间:2015-07-26 14:23:44

标签: matlab optimization minimum

考虑两条曲线,例如:

x = [1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20];
y1 = [0 0 -0.3 -0.8 -1.1 -1 -0.5 1 1.1 1 -0.3 -0.8 -1.1 -1 -0.5 0.1 0.05 0 0 0];
y2 = [0 -0.2 -0.3 -0.8 -2 1 2.8 2.4 1.5 1.1 2.3 -0.4 -0.2 1 1.1 1.2 1.3 0.5 -0.1 0];

enter image description here

我想编写一个广义算法,它接收xy1y2,并按全局比例因子{{1}缩放y1 }},以使f的新值尽可能接近y2-y1。也就是说,0尽可能接近0。

我该怎么做?

1 个答案:

答案 0 :(得分:1)

试试这个:

% Create a function that you want to minimize
func = @(f, y1, y2)abs(sum(y2 - f*y1));

% Your example data
x = [1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20];
y1 = [0 0 -0.3 -0.8 -1.1 -1 -0.5 1 1.1 1 -0.3 -0.8 -1.1 -1 -0.5 0.1 0.05 0 0 0];
y2 = [0 -0.2 -0.3 -0.8 -2 1 2.8 2.4 1.5 1.1 2.3 -0.4 -0.2 1 1.1 1.2 1.3 0.5 -0.1 0];

% Plot the before
figure()
plot(x, y2); hold all;
plot(x, y1)

% Find the optimum scale factor
f_start = 0; % May want a different starting point
f = fminsearch(@(f) func(f, y1, y2), f_start);
disp(['Scale factor = ' num2str(f)]) % print to the output 

% Plot the after (scaled data)
figure()
plot(x, y2); hold all;
plot(x, f*y1)

有关详细信息,请参阅anonymous functionsfminsearch上的文档(参见示例#2)。

修改

以下是上述脚本的输出:

  

比例因子= -2.9398

Before之前

After之后

正如您所看到的,函数之间的差异被最小化(y1大于y2的区域与y1小于y2的区域大致相同)。如果您希望线条尽可能接近匹配,则需要修改最小化函数,如下所示:

func = @(f, y1, y2)sum(abs(y2 - f*y1));

我必须修改此案例的测试数据,因为看起来数据已经最佳排列。

y1 = [0 0 -0.3 -0.8 -1.1 -1 -0.5 1 1.1 1 -0.3 -0.8 -1.1 -1 -0.5 0.1 0.05 0 0 0];
y2 = -2*y1 +1;

给出以下输出:

  

比例因子= -2.9091

enter image description here之前

enter image description here之后