Determining Ties in Mode of Matrix

조회 수: 4 (최근 30일)
Bradley Flynn
Bradley Flynn 2016년 2월 13일
댓글: Bradley Flynn 2016년 2월 15일
Let's say I have a matrix
A = [1 2 3 4
2 3 4 1
1 2 3 4
2 5 5 1]
and I take the mode of A
[M, F, C] = mode(A)
How would I go about selecting only the values in M where there was a tie and then replacing only those values? I've read that
cellfun('length',C) > 1
would tell you what values in M would have a tie, but I'm not sure how to incorporate that into replacing only the certain values where ties occurred.

답변 (1개)

Image Analyst
Image Analyst 2016년 2월 13일
This will do it:
A = [1 2 3 4
2 3 4 1
1 2 3 4
2 5 5 1]
% Find the mode of A. It will be 1.
modeOfA = mode(A(:))
% Find elements where the mode is
modeLocations = A == modeOfA
% Replace mode with 99
A(modeLocations) = 99
If you want it done all in one cryptic, harder to follow, but compact single line of code, you can do this:
A(A==mode(A(:))) = 99
  댓글 수: 3
Image Analyst
Image Analyst 2016년 2월 13일
Tell us what you would like to see as an output. What do you want to replace the mode value with?
If it's 99, then try this code:
A = [1 2 3 4
2 3 4 1
1 2 3 4
2 5 5 1]
for col = 1 : size(A, 2)
thisColumn = A(:, col);
% Find the mode of A. It will be 1.
modeOfA = mode(thisColumn)
% Find elements where the mode is
modeLocations = thisColumn == modeOfA
% Replace mode with 99
A(modeLocations, col) = 99
end
Bradley Flynn
Bradley Flynn 2016년 2월 15일
I'm trying to code my own knn and I want a good way to resolve ties without a for-loop. I did some thinking and came up with this if you're interested:
[preds, F, C]= mode(class);
if ~(all(cellfun('length',C)==1))
keep = cellfun('length',C)==1;
remove = cellfun('length',C) > 1;
preds = preds.*keep;
updated = remove.*knnclassifier(xTr,yTr,xTe,k-1);
preds = preds + updated;
end

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

카테고리

Help CenterFile Exchange에서 Pattern Recognition and Classification에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by