The usage of find in matlab for finding the length of repeated element

6 ビュー (過去 30 日間)
yuese zheng
yuese zheng 2015 年 7 月 31 日
編集済み: Andrei Bobrov 2015 年 7 月 31 日
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 件のコメント
per isakson
per isakson 2015 年 7 月 31 日
編集済み: per isakson 2015 年 7 月 31 日
See RunLength by Jan Simon and test your code with a few different vectors, x

サインインしてコメントする。

回答 (3 件)

Azzi Abdelmalek
Azzi Abdelmalek 2015 年 7 月 31 日
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)

Andrei Bobrov
Andrei Bobrov 2015 年 7 月 31 日
編集済み: Andrei Bobrov 2015 年 7 月 31 日
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})];

Image Analyst
Image Analyst 2015 年 7 月 31 日
編集済み: Image Analyst 2015 年 7 月 31 日
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.

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by