2012-08-17 21 views
2

的起始(以及偏移):找到给出的以下单元阵列数序列

strings = {'str1', 'str2', 'str2', 'str1', 'str2', 'str2', 'str1', 'str1', 'str2'}; 

我想找到起始点和一个特定的值的偏移(第一次出现和最后出现)。例如,以下是“STR1”的开始及偏移:

onset_str1 = [1, 4, 7, ]; 
offset_str1 = [1, 4, 8, ]; 

这里是“STR2”的导通和偏移:

onset_str2 = [2, 5, 9]; 
offset_str2 = [3, 6, 9]; 

目前,我做这样的事情:

[blub, ia, ic] = unique(strings, 'first'); 
all_str1 = find(ic == 1); % 1  4  7  8 
all_str2 = find(ic == 2); % 2  3  5  6  9 

使用all_str1all_str2然后我会看看连续值(使用diff为例),并确定方式上和偏移。然而,这种实现对我来说是'骇客'。

还有什么其他方法可以有效地提取序列中的偏移和偏移?

回答

1
[blub, ia, ic] = unique(strings, 'first'); 

确定,但接下来,只要使用逻辑值和find找到上升/下降沿:

N = numel(blub); % number of unique strings found 
str_onsets=cell(N,1); 
str_offsets=cell(N,1); 
for ii=1:N 
    x=ic==ii; 
    str_onsets{ii} = find([true ~x(1:end-1)] & x); 
    str_offsets{ii}= find(x & [~x(2:end) true]); 
end 

strfind如果这是更清楚地了解你:

N = numel(blub); % number of unique strings found 
str_onsets=cell(N,1); 
str_offsets=cell(N,1); 
for ii=1:N 
    x=ic==ii; 
    str_onsets{ii} = strfind([0 x],[0 1]); 
    str_offsets{ii}= strfind([x 0],[1 0]); 
end 
+0

你能解释一下'[true〜x(1:end-1)]'的部分吗? – memyself 2012-08-17 17:33:40

+1

找到'x'中的位置从0到1的转换,最初是'[0 x(1:end-1)] == false&x == true' (这是相同的)。你不能只用'x(1:end-1)== false&x(2:end)== true)',因为那样你会错过'x(1)= true'的情况发病。 – 2012-08-17 17:37:30