2012-04-16 44 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