Info

此问题已关闭。 请重新打开它进行编辑或回答。

If a number pops up again in a row.

1 次查看(过去 30 天)
James Connor
James Connor 2015-10-24
关闭: MATLAB Answer Bot 2021-8-20
How do I find the first number in a row that repeats itself and what position it was. For example, say I have a row x=[0 20 60 40 50 10 30 20] the first number to repeat itself is 20 and its the second number in the row so I would like my answer to be 2. Or take take something like y=[5 8 4 2 3 3 3] the first number to repeat its self is 3 and it does so as the 5th number so I would like the answer to be 5. Is there a general way to find the position of the first repeated number in a 1 row vector. Thank you.

回答(2 个)

the cyclist
the cyclist 2015-10-24
I think this will do what you want:
y = [0 20 60 40 50 10 30 20];
% y = [5 8 4 2 3 3 3];
[u,i,j] = unique(y,'stable');
c = histcounts(j,[i; Inf]);
position = find(c>1,1);
value = u(position);
value is the first repeated value, and position is the position of its first occurrence.

Star Strider
Star Strider 2015-10-24
编辑:Star Strider 2015-10-24
This works:
x=[0 20 60 40 50 10 30 20];
y=[5 8 4 2 3 3 3];
[Ux,xa,xc] = unique(x,'stable'); % Unique Numbers
fr_x = accumarray(xc,1); % Frequencies
Result_x = [Ux(fr_x>1), xa(fr_x>1)] % Number & Position In Vector
[Uy,ya,yc] = unique(y,'stable'); % Same, But For ‘y’
fr_y = accumarray(yc,1);
Result_y = [Uy(fr_y>1), xa(fr_y>1)]
Result_x =
20 2
Result_y =
3 5

此问题已关闭。

Community Treasure Hunt

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

Start Hunting!

Translated by