How can I check if indices in a single array equal each other?

1 view (last 30 days)
I'm creating a random array and I want to see if two or more numbers in that array equal each other.
For example, if I get [1 8 6 4 6] I want to know which numbers are equal (which are the two 6's).
I'm doing this because I want to create another array that has the equal numbers and get other random numbers.
So, if I had [1 8 6 4 6] I want to keep the 6's and randomize the other numbers so the next array would be (for example) [5 9 6 1 6] or [6 2 6 3 6], etc.
What's a simple way I can do this without making a bunch of if statements?
Thank you so much!!!
  2 Comments
John D'Errico
John D'Errico on 10 May 2015
Edited: John D'Errico on 10 May 2015
Please don't do this. Deleting your question insults the person who wasted their time answering YOUR question, by preventing that same answer being useful for anyone else in the future.

Sign in to comment.

Accepted Answer

Joseph Cheng
Joseph Cheng on 10 May 2015
you can do this with one if statement and possible no if statements if i spent more time but this should do the trick. by using the outputs of the function unique one can determine what items are unique and then go through and highlight which ones should be kept. Then take the inverse of what you want to keep and use that to define which index positions you want to swap.
x= [1 8 8 6 4 6 2 1 8 8];
[a b c] = unique(x,'stable')
keep = zeros(size(x));
for ind = 1:length(a)
match = x == x(b(ind));
if sum(match)>1
keep = keep+match
end
end
toswap = ~keep;
replace = randi(10,1,sum(toswap));
x(toswap) = replace

More Answers (0)

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!