2017-08-26 202 views
0

我試圖在matlab上執行下面的代碼我在函數內部有一個for循環,它應該在每次迭代中都存儲一個結果,但是當它執行時它只是給了我最後一次迭代的結果,是否有代碼序列有問題? 的INPIT DATA1是大小(33167 * 1) 的數據矢量I懷疑有sometnig錯與福爾環..有我寫的代碼:matlab中for循環的意外輸出

function [vectorDominant] = processData(data1 , samplingRate , startRange, endRange) 
    %(length(data)/1000) 
data = data1; 
windowSize = 10; 
samplingRate = samplingRate; 
frame_len = samplingRate*windowSize; 
l = length(data); 
num_frames = floor(l/frame_len); 
t = 1; 

    for i = 1 : num_frames 
        frame = data((i-1)*frame_len+1 : frame_len*i); 

        % --- haming window ------ 

        hammingData=frame.*hamming(length(frame)); 

        %---- remove dc offset from data ---- 

        dataWindowed = detrend(hammingData); 

        % ---- apply fft ---- 


        fourierTransform_data=fft(dataWindowed); 
        y = fourierTransform_data ; 

        %plot(abs(fourierTransform_data)) 



        %------- find dominant----- 


       len = (length(frame)/2) -1; 

        y = y(1:len); 
        [v,k] = max(y); 


       fftLength = length(frame); 
       freq = (0:(samplingRate/fftLength) :(samplingRate/2)); 


       %plot(freq,abs(y)), grid('on'), title('dominant freq') 
       freq = freq(find(freq>=startRange & freq<=endRange)); 
       dominantFrequency = freq(k); 

       %array[(length(data)/1000)]; 
       %var = 1; 
       %while var<= length(num_frames) 
        n = (length(data)/1000); 

        vectorDominant = zeros(n,1); % to preallocate it first as it changes size every iterartion 
        vectorDominant(i) = dominantFrequency; 
        %var = var+1; 


        %end 



    end 


end 

參數我給它是過程數據(AX,100,0.1%,2)其中斧是 數據向量和它返回下列ANS =

 0 
    0 
    0 
    0 
    0 
    0 
    0 
    0 
    0 
    0 
    0 
    0 
    0 
    0 
    0 
    0 
    0 
    0 
    0 
    0 
    0 
    0 
    0 
    0 
    0 
    0 
    0 
    0 
    0 
    0 
    0 
    0 
0.2000 

整個結果必須有像最後一個(0.2000)號不爲零

回答

1

每次在循環中重新創建vectorDominant爲零向量,然後將它的一個元素設置爲新計算的值。在進入循環之前,推測下列行中的前2行應該完成一次。

n = (length(data)/1000); 
vectorDominant = zeros(n,1); 
vectorDominant(i) = dominantFrequency; 

想必n也應該是不num_frames上面計算的值。