如何根据峰值将数据集分成三个不同的向量
How to divide a data set into three different vectors based on peaks
我有一个大数据集,在绘制图表时,它类似于具有三个峰值的 sin(x)+1 图表。我想在每个峰下进行整合,得到三个不同的区域。我不知道峰值的坐标位置,也不能假设我知道波长。所以我需要找到三个峰值并将数据分成三个对应的向量。任何帮助将不胜感激。
您可以使用 findpeaks
函数完成您想要的。举个例子:
我们生成数据的两个向量 x
和 y
:
x = linspace(0, 5*pi); % x data.
y = sin(x) + 1; % y data.
然后我们使用 findpeaks
找到数据集的峰值并检索它们的索引 (locs
):
>> [~, locs] = findpeaks(y)
locs =
11 51 90
我们可以看到该函数找到了 3 个坐标为 [x(11), y(11)]
、[x(51), y(51)]
和 [x(90), y(90)]
.
的峰
通过在没有输出参数的情况下调用 findpeaks
,我们可以获得覆盖峰值的数据图,这对于视觉验证通常很有用:
>> findpeaks(y)
我们可以很容易地用下面的方法划分我们的数据集 for
loop, and store the different subsets in a cell array:
n = numel(locs);
for i = 1:n + 1
if i == 1
x_cell{i} = x(1:locs(i));
y_cell{i} = y(1:locs(i));
elseif i <= n
x_cell{i} = x(locs(i-1):locs(i));
y_cell{i} = y(locs(i-1):locs(i));
else
x_cell{i} = x(locs(i-1):end);
y_cell{i} = y(locs(i-1):end);
end
end
这会给我们:
K>> x_cell
x_cell =
1×4 cell array
[1×11 double] [1×41 double] [1×40 double] [1×11 double]
和
K>> y_cell
y_cell =
1×4 cell array
[1×11 double] [1×41 double] [1×40 double] [1×11 double]
所以我们已经成功地划分了我们的数据集。每个单元格包含原始数据集的一个子集。
现在我们可以在 for
循环中使用 trapz
来计算每个子集的数值积分:
k = numel(y_cell);
for i = 1:k
A(i) = trapz(x_cell{i}, y_cell{i});
end
这些是结果:
>> A
A =
2.6004 6.4099 6.0931 2.6004
最后我认为使用 area
函数和 for
循环将不同区域绘制在一起会很好:
hold on;
for i = 1:k
area(x_cell{i}, y_cell{i}, 'FaceColor', i/k*[1, 1, 1]);
end
hold off; axis tight;
grid on; box on;
这里可以清楚地看到不同的区域:
我有一个大数据集,在绘制图表时,它类似于具有三个峰值的 sin(x)+1 图表。我想在每个峰下进行整合,得到三个不同的区域。我不知道峰值的坐标位置,也不能假设我知道波长。所以我需要找到三个峰值并将数据分成三个对应的向量。任何帮助将不胜感激。
您可以使用 findpeaks
函数完成您想要的。举个例子:
我们生成数据的两个向量 x
和 y
:
x = linspace(0, 5*pi); % x data.
y = sin(x) + 1; % y data.
然后我们使用 findpeaks
找到数据集的峰值并检索它们的索引 (locs
):
>> [~, locs] = findpeaks(y)
locs =
11 51 90
我们可以看到该函数找到了 3 个坐标为 [x(11), y(11)]
、[x(51), y(51)]
和 [x(90), y(90)]
.
通过在没有输出参数的情况下调用 findpeaks
,我们可以获得覆盖峰值的数据图,这对于视觉验证通常很有用:
>> findpeaks(y)
我们可以很容易地用下面的方法划分我们的数据集 for
loop, and store the different subsets in a cell array:
n = numel(locs);
for i = 1:n + 1
if i == 1
x_cell{i} = x(1:locs(i));
y_cell{i} = y(1:locs(i));
elseif i <= n
x_cell{i} = x(locs(i-1):locs(i));
y_cell{i} = y(locs(i-1):locs(i));
else
x_cell{i} = x(locs(i-1):end);
y_cell{i} = y(locs(i-1):end);
end
end
这会给我们:
K>> x_cell
x_cell =
1×4 cell array
[1×11 double] [1×41 double] [1×40 double] [1×11 double]
和
K>> y_cell
y_cell =
1×4 cell array
[1×11 double] [1×41 double] [1×40 double] [1×11 double]
所以我们已经成功地划分了我们的数据集。每个单元格包含原始数据集的一个子集。
现在我们可以在 for
循环中使用 trapz
来计算每个子集的数值积分:
k = numel(y_cell);
for i = 1:k
A(i) = trapz(x_cell{i}, y_cell{i});
end
这些是结果:
>> A
A =
2.6004 6.4099 6.0931 2.6004
最后我认为使用 area
函数和 for
循环将不同区域绘制在一起会很好:
hold on;
for i = 1:k
area(x_cell{i}, y_cell{i}, 'FaceColor', i/k*[1, 1, 1]);
end
hold off; axis tight;
grid on; box on;
这里可以清楚地看到不同的区域: