필터 지우기
필터 지우기

Keeping check of how many times a loop has seen a repeated value

조회 수: 4 (최근 30일)
luc
luc 2015년 6월 4일
편집: Guillaume 2015년 6월 4일
Hey everyone!
I've been playing around with the unique function for a while now, but I can't seem to simply solve this problem.
In my code I've commented and shown what I want to achieve. basicly I've got a matrix where the first 2 columns are unique values (say integer X&Y data) and the last column indicates how often I've come across those values before.
But no avail!
Thanks in advance!
D=[3 1 1]';
B=[2 0 1]';
T_seen=[100 1 1]'; %amount of time these values have been seen before, so the row [3 2] has been seen 100x before
A=[D B T_seen] %old values
A_d=[1 0;1 2;1 2] %new values which need to be added to the old values after removing duplicates
A_d=[A_d ones(size(A_d,1),1)] %adding 1's to the last column to indicate they have been seen once (now)
A_new=[A;A_d] %making one matrix of old and new combined
%with the last column indicating how many times they've been seen
[C, Ia,Ic]=unique(A_new(:,[1:end-1]),'rows'); %removing duplicate values from the matrix. (ignoring the amount of times they've been seen)
C
display('now. The goal is to create a matrix that looks like this:')
goal=[C [2;1;2;100]]
pause
%Here's my failed code:
New_A_d=A_new(Ia,:);
A0_A_d=[zeros(size(A,1),1);A_d(:,end)] %trying to replaces ones for zeros does not work either.
display('start')
for n=1:size(Ic,1)
n;
indice=Ic(n);
New_A_d(indice,end)=New_A_d(indice,end)+A0_A_d(indice)
%New_A_d(indice,end)=New_A_d(indice,end)+1 %does not work either
end

채택된 답변

Guillaume
Guillaume 2015년 6월 4일
accumarray is perfect for this:
[C, ~, idx] = unique(A_new(:, 1:end-1), 'rows');
[C accumarray(idx, A_new(:, end))]
  댓글 수: 2
luc
luc 2015년 6월 4일
Nice! How the hell does it work?
Guillaume
Guillaume 2015년 6월 4일
편집: Guillaume 2015년 6월 4일
The 3rd return value of unique maps each row to an index. identical rows map to the same index.
accumarray sums together values in the last column that map to the same index. Sums are returned in the same order as the indices, which is the same order as the 1st return value of unique.
See the documentation of accumarray (linked in my answer).

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

dpb
dpb 2015년 6월 4일
I think your counting is off by one in that you need the initialization to be zero until do the counting...consider
>> histc(Ic,unique(Ic))
ans =
2
1
2
1
>>
Is the correct count for the new rows; you've got to then add for the existing.
  댓글 수: 1
luc
luc 2015년 6월 4일
I'm sorry, I don't quite understand. Say the start value of the original coordinates are 1,1,1,1. Then the amount of seen points should be: [2 1 3 0], not [2 1 2 1]. (the 3 comes from the double [1 2] in the newly added data).

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by