フィルターのクリア

How to search for a previous element that is equal in prior loop iteration

2 ビュー (過去 30 日間)
Tim Baker
Tim Baker 2015 年 12 月 28 日
コメント済み: Tim Baker 2015 年 12 月 29 日
I have a Matrix called A as below
[1 1 3;
1 2 2;
1 3 3;
2 1 1;
2 2 3;
2 3 2;
2 4 4]
I want to produce a column vector that counts the number of times a value occurs in the 2nd column, I have tried the following function :
function count_stars(A)
total = 0;
for i = 1:size(A,1)
total = total + (A(i,2)==A(:,2));
end
total
This counts the number of matching values in the entire column e.g.
2
2
2
2
2
2
1
What I am wanting is to match to values between 1:i only rather than the entire column so that the output looks like this
1
1
1
2
2
2
1
Any insights you are able to share are greatly appreciated!
  2 件のコメント
Image Analyst
Image Analyst 2015 年 12 月 28 日
It's too late at night for me to work on this, but I'm thinking it might involve accumarray(), cumsum() or histcounts(). A question though, will the numbers always be integers? Or might they be floating point numbers with fractional parts?
Tim Baker
Tim Baker 2015 年 12 月 28 日
Thanks for your response, yes the numbers are always integers. Am interested in discovering other ways to solve the problem if it can be done more efficiently. Harjeet's solution works well.

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

採用された回答

harjeet singh
harjeet singh 2015 年 12 月 28 日
hello tim try this code
a=[1 1 3;
1 2 2;
1 3 3;
2 1 1;
2 2 3;
2 3 2;
2 4 4];
for i=1:size(a,1)
[r,c]=find(a(1:i,2)==a(i,2));
b(i,1)=length(r);
end
b
  1 件のコメント
Tim Baker
Tim Baker 2015 年 12 月 28 日
Thanks Harjeet for your prompt answer, its works a treat.

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

その他の回答 (1 件)

Guillaume
Guillaume 2015 年 12 月 29 日
For small arrays, it does not matter but this is likely to be more efficient than harjeet's answer for large arrays:
a = [1 1 3;
1 2 2;
1 3 3;
2 1 1;
2 2 3;
2 3 2;
2 4 4];
[values] = unique(a(:, 3));
counts = zeros(size(a, 1), 1);
for val = values';
occurences = cumsum(a(:, 3) == val);
counts(a(:, 3) == val) = occurences(a(:, 3) == val);
end
Rather than looping over all the rows of a, it only loops over the unique values of a (4 iterations instead of 7 in this example).
  1 件のコメント
Tim Baker
Tim Baker 2015 年 12 月 29 日
Wow! Your approach is significantly faster, thanks for your response.

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

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by