Get rid of an unwanted zero element in an IF loop

1 回表示 (過去 30 日間)
Agent Cooper
Agent Cooper 2014 年 5 月 5 日
コメント済み: Azzi Abdelmalek 2014 年 5 月 5 日
I'm trying to create a function that returns only the elements in a vector which repeats exactly three times using the following code:
function y = three_times(x)
a = sort(x)
b = unique(a)
for i = 1:numel(b)
c = find(b(i) == a)
d = length(c)
if d == 3
e(i) = b(i)
end
end
y = e
If I apply this function to a vector like
x = [1 2 5 2 2 7 8 3 3 1 3 8 8 8]
I get y = [0 2 3] instead of y = [2 3]. Any hints on how can I repair this?

採用された回答

Azzi Abdelmalek
Azzi Abdelmalek 2014 年 5 月 5 日
x = [1 2 5 2 2 7 8 3 3 1 3 8 8 8]
[freq,a]=hist(x,unique(x))
out=a(freq==3)
  2 件のコメント
Agent Cooper
Agent Cooper 2014 年 5 月 5 日
Azzi,
Thank you very much for your very elegant and compact code. It works just fine.
However, I would be grateful if you (or anyone else) could also give me a hint regarding the problem in my code.
Azzi Abdelmalek
Azzi Abdelmalek 2014 年 5 月 5 日
Ok, first
a = sort(x)
b = unique(a)
is equivalent to
b=unique(x)
because, by default the function unique will sort your result
Use numel(b) instead of length(b). In your case they give the same result.
The hint for your problem is the counter i you are using. Because d is not always equal to 3, when for example i=1 is skipped, you will get e(1)=0; to avoid this problem, use another counter, for example
k=0
If d==3
k=k+1
%do
end

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

その他の回答 (0 件)

カテゴリ

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

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by