For example I have a one vector:
y = [21 19 15 17 18 19 25 36 48 19 19]'
In y vector I have a recurring element 19. And I should another vector, in which all elements are equal to one, but if the element has already met for the second time or greater, then assign it a value of zero:
l = [1 1 1 1 1 0 1 1 1 0 0]'
How to do this?
CodePudding user response:
The second output of unique
tells you when a number appears for the first time; that is, which positions in the result should be set to 1
:
y = [21 19 15 17 18 19 25 36 48 19 19]';
[~ ,v] = unique(y, 'stable');
l = zeros(size(y));
l(v) = 1;
Another approach, using implicit expansion, is as follows. This is less efficient because it computes an intermediate N×N matrix, where N is the size of the input:
y = [21 19 15 17 18 19 25 36 48 19 19]';
l = ~any(triu(y==y.', 1), 1).';