如何使用matlab计算列中相同的数字值
How to count same values of number in column using matlab
所以这是我的问题,我想计算列中相同值的数量,这是我的数据:
a b d
2 1 5
1 3 10
1 -2 5
0 5 25
5 0 25
1 1 2
-1 -1 2
我想计算 d 的相同值(其中 d = a^2 + b^2),所以这是我想要的输出:
a b d count
2 1 5 2
1 3 10 1
0 5 25 2
1 1 2 2
如您所见,仅显示 a 和 b 的正组合。那我该怎么做呢?谢谢。
假设您的输入数据存储在二维数组中,这可能是一种方法 -
%// Input
A =[
2 1 5
1 3 10
1 -2 5
0 5 25
5 0 25
1 1 2
-1 -1 2]
[unqcol3,unqidx,allidx] = unique(A(:,3),'stable')
counts = sum(bsxfun(@eq,A(:,3),unqcol3.'),1) %//'
out =[A(unqidx,:) counts(:)]
您还可以使用 histc
-
获取计数
counts = histc(allidx,1:max(allidx))
关于 a
和 b
的正组合的注意事项: 如果您想要 A
和 [=17 的正组合=],您可以 select 只有 A
中满足此要求的那些行,并作为预处理步骤保存回 A
-
A = A(all(A(:,1:2)>=0,2),:)
假设您的数据是一个矩阵,这里是一个基于accumarray
的方法。请注意,这并未满足 "only positive combinations of a and b displayed".
的要求
M = [2 1 5
1 3 10
1 -2 5
0 5 25
5 0 25
1 1 2
-1 -1 2]; %// data
[~, jj, kk] = unique(M(:,3),'stable');
s = accumarray(kk,1);
result = [M(jj,:) s];
所以这是我的问题,我想计算列中相同值的数量,这是我的数据:
a b d
2 1 5
1 3 10
1 -2 5
0 5 25
5 0 25
1 1 2
-1 -1 2
我想计算 d 的相同值(其中 d = a^2 + b^2),所以这是我想要的输出:
a b d count
2 1 5 2
1 3 10 1
0 5 25 2
1 1 2 2
如您所见,仅显示 a 和 b 的正组合。那我该怎么做呢?谢谢。
假设您的输入数据存储在二维数组中,这可能是一种方法 -
%// Input
A =[
2 1 5
1 3 10
1 -2 5
0 5 25
5 0 25
1 1 2
-1 -1 2]
[unqcol3,unqidx,allidx] = unique(A(:,3),'stable')
counts = sum(bsxfun(@eq,A(:,3),unqcol3.'),1) %//'
out =[A(unqidx,:) counts(:)]
您还可以使用 histc
-
counts = histc(allidx,1:max(allidx))
关于 a
和 b
的正组合的注意事项: 如果您想要 A
和 [=17 的正组合=],您可以 select 只有 A
中满足此要求的那些行,并作为预处理步骤保存回 A
-
A = A(all(A(:,1:2)>=0,2),:)
假设您的数据是一个矩阵,这里是一个基于accumarray
的方法。请注意,这并未满足 "only positive combinations of a and b displayed".
M = [2 1 5
1 3 10
1 -2 5
0 5 25
5 0 25
1 1 2
-1 -1 2]; %// data
[~, jj, kk] = unique(M(:,3),'stable');
s = accumarray(kk,1);
result = [M(jj,:) s];