The usage of find in matlab for finding the length of repeated element
6 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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.
1 commentaire
Réponses (3)
Azzi Abdelmalek
le 31 Juil 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 commentaires
Andrei Bobrov
le 31 Juil 2015
Modifié(e) : Andrei Bobrov
le 31 Juil 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 commentaires
Image Analyst
le 31 Juil 2015
Modifié(e) : Image Analyst
le 31 Juil 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 commentaires
Voir également
Catégories
En savoir plus sur Matrix Indexing dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!