The usage of find in matlab for finding the length of repeated element
1 view (last 30 days)
Show older comments
Let' say I have a vector [1 1 1 2 2]. I want to know what elements are repeated, and repeated for how many times. Basically, I want the program to tell me 1s and 2s are repeated, and 1s are repeated 3 times, and 2s are repeated 2 times. So far,
index=[find(x(1:end-1) ~= x(2:end))];
len=diff([0 index]);
gives me a value of 3 and 2 respectively, which is what I want for the number of times each element is repeated. However, I am not sure how the "find" function is doing its job here. Could anyone explain to me? I checked the find function docs but no luck. Thank you.
Answers (3)
Azzi Abdelmalek
on 31 Jul 2015
In your case find is not doing the job, your code doesn't give the expected result
x=[1 1 1 2 2];
index=[find(x(1:end-1) ~= x(2:end))];
len=diff([0 index]);
The result
index =
3
len =
3
This is one way to do it:
x=[1 1 1 2 2];
[~,~,kk]=unique(x);
out=accumarray(kk,1)
0 Comments
Andrei Bobrov
on 31 Jul 2015
Edited: Andrei Bobrov
on 31 Jul 2015
a = unique(x(:));
out = [a,histcounts(x,[a,a(end)+1])'];
for v = [1, 1, 1, 2, 2, 1, 1, 7, 7, 4, 4, 4, 2]';
i0 = [true;diff(v)~=0];
ii = cumsum(i0);
t = [v(i0),accumarray(ii,1)];
[a,~,c] = unique(t(:,1));
out = [num2cell(a),num2cell(accumarray(c,1)),accumarray(c,t(:,2),[],@(x){x})];
0 Comments
Image Analyst
on 31 Jul 2015
Edited: Image Analyst
on 31 Jul 2015
Try this:
vector = [1, 1, 1, 2, 2, 1, 1, 7, 7, 4, 4, 4, 2]
for k = unique(vector)
measurements = regionprops(vector == k, 'Area');
numberOfRegions = length(measurements);
fprintf('%d occurs in %d regions with lengths: ', k, numberOfRegions);
allLengths = [measurements.Area];
fprintf('%d, ', allLengths);
fprintf('\n'); % Go to the next line.
end
Output in the command window:
vector =
1 1 1 2 2 1 1 7 7 4 4 4 2
1 occurs in 2 regions with lengths: 3, 2,
2 occurs in 2 regions with lengths: 2, 1,
4 occurs in 1 regions with lengths: 3,
7 occurs in 1 regions with lengths: 2,
It has the advantage over the other methods in that it will work where the same number is separated into 2 or more regions (like in the vector example I show), whereas the other methods don't. However you need the Image Processing Toolbox to use this method, but that's a very common toolbox.
0 Comments
See Also
Categories
Find more on Logical 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!