pairs of consecutive numbers

5 ビュー (過去 30 日間)
Lenin Cruz
Lenin Cruz 2019 年 8 月 21 日
コメント済み: Ancalagon8 2022 年 12 月 9 日
Hello,
I have a vector A=[1 2 5] i would like to have something that stores the pair of consecutive numbers eg B= [1 2] and something that stores the values unused eg [C= 5]
i would like this working for A=[5 2 1], A=[5 1 2] and all the permutations of the elements .
Thanks
Here is some piece of code that I have tried but I have no idea how to get the element unused, 'C' in my example above
A= [6 3 4];
p=[find(diff(A)==1); find(diff(A) == -1)];
q=[p;p+1];
A(q)
  1 件のコメント
Andrei Bobrov
Andrei Bobrov 2019 年 8 月 21 日
Please set your result for [1 2 3 4 5 4 3].

サインインしてコメントする。

採用された回答

Guillaume
Guillaume 2019 年 8 月 21 日
Well, you're almost there. When the diff is 1 or -1, this means that the number at the same index and the next one are consecutive. The easiest way to find the non-consecutive numbers is to take the set difference of all the indices with the pair indices.
A = [6 2 3 2 4 1 3 2 1 0 5]
pairindices = find(ismember(diff(A), [-1, 1])) + [0;1] %assumes A is a row vector
nonconsindices = setdiff(1:numel(A), pairindices)
Another method, which uses the undocumented feature that strfind works with numeric vectors:
nonconsindices = strfind([0, abs(diff(A)) == 1, 0], [0, 0])
  13 件のコメント
Stephen23
Stephen23 2022 年 12 月 9 日
"from row position 14 to 19, 33 to 36 etc to assign these number to dates (14-Jan to 19-Jan, 02-Febr to 05-Febr)"
V = [14;19;33;36];
D = datetime(2022,1,V)
D = 4×1 datetime array
14-Jan-2022 19-Jan-2022 02-Feb-2022 05-Feb-2022
Ancalagon8
Ancalagon8 2022 年 12 月 9 日
@Stephen23 thank you very much!

サインインしてコメントする。

その他の回答 (2 件)

Rik
Rik 2019 年 8 月 21 日
I have expanded your example array a bit to more clearly show the indeded effect. I have replicated the effect of your code, please confirm that is what you meant.
A=[3 1 2 0 3 4 5];
L= abs(diff(A))==1;
L=[L false;false L];
L_unused= sum(L,1)==0 ;
B=[A(L(1,:));A(L(2,:))];
C=A(L_unused);
  2 件のコメント
Lenin Cruz
Lenin Cruz 2019 年 8 月 21 日
Thanks for your reply. Yes, that is similar to what my code does, but let's say that now
A=[5 3 4 1];
I would expect my matrix B to be: B=[3 4; 4 5]
but I am just getting B=[3;4]
Any advice on how to do that? Thanks
Rik
Rik 2019 年 8 月 21 日
The solution is the same as with the other method: sort A beforehand.

サインインしてコメントする。


Bruno Luong
Bruno Luong 2019 年 8 月 21 日
編集済み: Bruno Luong 2022 年 11 月 29 日
A=[5 3 4 1];
As=sort(A);
b=diff(As)==1;
pairs=As(b)'+[0 1];
notpair = setdiff(A,pairs(:))
notpair = 1

カテゴリ

Help Center および File ExchangeShifting and Sorting Matrices についてさらに検索

タグ

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by