2012-04-16 119 views
0

您好我想找到一种方法来创建一个在MatLab中的矩阵,只有在30秒内重复的练习的最大值和最小值。MatLab中的数据集的最大和最小点

举例来说,如果我有数据集:

data = [1 3 5 7 9 6 4 2 3 6 8 10 7 6 4 2 1] 

我想要的结果将是:

output = [1 9 2 10 1] 

功能只能绘制一个不断变化的波形的峰值。

我已经试过代码如下:

size = length(data); %Get the length of the dataset 
x = 1;     %Set a counter value 
maxplot = 0;   %Default, a maximum value has not yet been plotted 

for x = 1:size-1 
    a1 = data(1,x);  %Get two adjacent samples of the dataset 
    a2 = data(1,x+1); 

    v = 1; %Set the initial column for the max points matrix 

    while maxplot == 0 
     if a1 > a2 
      max(v,1) = a1; 
      v = v + 1; 
      maxplot = 1; 
     end 
    end 

    if a1 < a2 
     maxplot = 0;  
    end 
end 

感谢谁提前回复,

贾里德。

+0

你试过只是写,做这样的功能?它看起来不那么难... – trutheality 2012-04-16 02:05:22

+0

我已经尝试过,但我是与MatLab合作的新手。我认为我无意中创建了一个无限循环,因为MatLab被卡住为'Busy' – jazibobs 2012-04-16 02:07:37

+0

你可以发布你已经尝试过的东西,并且有人可以帮助你... – trutheality 2012-04-16 02:09:03

回答

2

你可以使用这样的事情:

function Y = findpeaks(X) 
    deltas = diff(X); 
    signs = sign(deltas); 
    Y = [true, (signs(1:(end-1)) + signs(2:end)) == 0, true]; 

findpeaks将返回相同长度的逻辑阵列作为其输入X阵列。要提取标记值,只需按逻辑数组索引即可。

例如,

data = [1 3 5 7 9 6 4 2 3 6 8 10 7 6 4 2 1]; 
peaks = data(findpeaks(data)) 

应该输出:

peaks = 
    1 9 2 10 1 

此功能不会做什么特别的应对输入数组中重复的值。我把它作为读者的练习。

+0

它似乎失败时,在峰值平坦部分(即' ... 8 10 10 7 ...')。 – trutheality 2012-04-16 02:15:58

+0

@真理:真。我会添加一个注释。 – 2012-04-16 02:16:49

+0

谢谢,这绝对是完美的。我不知道在我失踪的“findpeaks”中有这样一个简单的选项。 – jazibobs 2012-04-16 02:18:01

2

这个版本并不像约翰的漂亮,但是当有平坦的部分它不会失去峰:

function peaks = findpeaks(data) 
% Finds the peaks in the dataset 

size = length(data); %Get the length of the dataset 
x = 1;     %Set a counter value 
peaks = data(1,1);  %Always include first point 

if size == 1 %Check for sanity 
    return 
end 

lastdirection = 0;  %Direction of change 

directions = sign(diff(data)); %Directions of change 
           % between neighboring elements 

while x < size 
    % Detect change in direction: 
    if abs(directions(x) - lastdirection) >= 2 
     peaks = [peaks, data(1,x)]; 
     lastdirection = directions(x); 
    else 
     % This is here so that if lastdirection was 0 it would get 
     % updated 
     lastdirection = sign(lastdirection + directions(x)); 
    end 
    x = x+1; 
end 

peaks = [peaks, data(1,size)]; 
end