如何改进包含多个if语句的以下语法?

时间:2017-02-13 20:24:19

标签: matlab if-statement syntax vectorization

我感兴趣的是找到信号开始,定义为信号偏离基线的点(即基线的平均值)并且永远不会回来。下面的代码在信号F中找到起始点,作为F的相邻元素的最新负差。然而,由于信号F中的一些噪声(我不想对其进行滤波),可以比预期(视觉上)检测到发作。

在以下信号F的示例中,“视觉右侧”起始位于点944处。然而,遵循上述方法,首先将其设置在点1001.

代码的后半部分,包括几个if语句,更正并搜索包含在所需F范围内的最新idx(在本例中为mean(baseline))。

如何改进这些if语句,以便它在idx向量中一个接一个地返回,直到F(开始)< = mean_baseline为TRUE?

样本信号F.mat可以在这里找到:https://www.dropbox.com/s/r4t8nzz4s7t9x4e/F.mat?dl=0

Fs = 1926; % sampling frequency 
ff = diff(F);
idx = find(ff < 0);
onset = idx(end); % here 

% Take a chunk of F prior to "onset": baseline
Fs = 1926; % sampling frequency
baseline = F(1:onset-(Fs*0.15)); % create baseline as a chunk of F, 150ms before the onset found above
mean_baseline = mean(baseline); % we create this variable to be used later as condition in the if statements

% we are interested in indexing the latest negative idx (idx < 0) BUT only if the corresponding F value is equeal or lower than the desired value (in this case mean_baseline)
if F(onset) > mean_baseline
    idx = find(ff < 0);
    onset = idx(end-1);
    if F(onset) > mean_baseline
        idx = find(ff < 0);
        onset = idx(end-2);
        if F(onset) > mean_baseline
            idx = find(ff < 0);
            onset = idx(end-3);
            if F(onset) > mean_baseline
                idx = find(ff < 0);
                onset = idx(end-4);
                if F(onset) > mean_baseline
                    idx = find(ff < 0);
                    onset = idx(end-5);
                    if F(onset) > mean_baseline
                        idx = find(ff < 0);
                        onset = idx(end-6);
                        if F(onset) > mean_baseline
                            idx = find(ff < 0);
                            onset = idx(end-7);
                            if F(onset) > mean_baseline
                                idx = find(ff < 0);
                                onset = idx(end-8);
                            end
                        end
                    end
                end
            end
        end
    end
end

1 个答案:

答案 0 :(得分:1)

我无法测试代码,因为我不知道所有变量,但也许可以这样做:

for ii = 1:size(ONSETS,2)
    baseline = F(ONSETS(ii)-500:ONSETS(ii)-50);
    max_baseline = max(baseline);

    idx = find(ini(:,ii) < 0);
    idxWorking = length(idx);
    while idxWorking > 0 & F(idx(idxWorking)) > max_baseline
        idxWorking = idxWorking-1;
    end
    ONSETS(1,ii) = idxWorking;
end

或者,您可以将函数F应用于idx的所有值,然后选择满足条件的最后一个值。

for ii = 1:size(ONSETS,2)
    baseline = F(ONSETS(ii)-500:ONSETS(ii)-50);
    max_baseline = max(baseline);

    idx = find(ini(:,ii) < 0);
    Fvalues = F(idx);
    ONSETS(1,ii) = idx(find(Fvalues<max_baseline,1,'last'));
end