loop through a column and display the number of elements until the same value occcurs

1 回表示 (過去 30 日間)
Hi,
how am I able to loop through a coulmn and get as the output the numbers of rowselement between the first and the next element which is equal to the first element. Here is an example, if this vector:
1
2
3
4
5
7
9
2
1
5
6
8
9
2
4
5
6
now I would like to loop through the column and display the number of elements between the two numbers which are equal.
I tried to use something like this: for i:numel(matrix_call)
for n:
if matrix(i,2)==matrix(i+n,2)
but I am not sure how to do that.
The output for the example I mentioned above should be a new vector which displays in which row the next element, which is equal to the one we are looking at, is following, such as:
vector:
9 (row in which the one is occuring for the second time)
8 (in row 8 there is the number "2" for the second time)
NaN (there is no second number "3")
15 (number "4" occcurs in line 15 for the second time)
and so on

採用された回答

Azzi Abdelmalek
Azzi Abdelmalek 2013 年 3 月 17 日
編集済み: Azzi Abdelmalek 2013 年 3 月 17 日
This gives the number of element between two consecutive same numbers.
EDIT
A=[1 2 3 4 5 7 9 2 1 1 5 6 8 9 2 4 5 6]'
m=numel(A);
out=nan(1,m);
numb=out;
for k=1:m
B=A(k:end);
idx=find(B==B(1),2);
n=numel(idx);
if n>1
out(k)=idx(2)-idx(1)+k;
numb(k)=numel(unique(B(idx(1)+1:idx(2)-1)));
end
end
[A out' numb']
  18 件のコメント
Locks
Locks 2013 年 3 月 17 日
how can I post a link/ how am I able to upload the data anywhere so I am able to post a link? I have posted another question including the data, I hope it is clearer what I am up to

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

その他の回答 (1 件)

Azzi Abdelmalek
Azzi Abdelmalek 2013 年 3 月 17 日
A=[1 2 3 4 5 7 9 2 1 5 6 8 9 2 4 5 6]'
for k=1:numel(A)
B=A(k:end)
idx=find(B==B(1))
n=numel(idx)
if n==1
out(k)=nan
else
out(k)=idx(2)-idx(1)+k
end
end
  1 件のコメント
Locks
Locks 2013 年 3 月 17 日
yes it is possible, in fact the same number occcurs more than 100 time and I need a vector to see where the next number which is equal to the one I am looking for is occuring. as a alternative, it woudl also be possible, I think, to create a matrix which shows the numbers of elements between the first time the numbers are equal, between 2nd and 3rd occurence etc.

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

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by