Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/69.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/matlab/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 包含与矩阵中每个元素对应的出现次数的矩阵_R_Matlab_Matrix - Fatal编程技术网

R 包含与矩阵中每个元素对应的出现次数的矩阵

R 包含与矩阵中每个元素对应的出现次数的矩阵,r,matlab,matrix,R,Matlab,Matrix,假设我有矩阵 A = [1 2 3 1 1 1 2 3] 我想找出这个数字出现在矩阵中的次数。该i/p的输出矩阵为 B = [1 1 1 2 3 4 2 2] i、 e.1在数组中出现了4次,因此对应于1的最后一个值是4 unique和sum unique没有帮助,因为它给出了元素发生的总次数,但我需要另一个矩阵,它会在每次发生时增加计数。尝试以下方法: B = ave(A,A,FUN=function(x) 1:length(x)) 您只需使用下面的代码就可以做到这一点。这将假设A矩阵是

假设我有矩阵

A = [1 2 3 1 1 1 2 3]
我想找出这个数字出现在矩阵中的次数。该i/p的输出矩阵为

B = [1 1 1 2 3 4 2 2]
i、 e.1在数组中出现了4次,因此对应于1的最后一个值是4

unique
sum unique
没有帮助,因为它给出了元素发生的总次数,但我需要另一个矩阵,它会在每次发生时增加计数。

尝试以下方法:

B = ave(A,A,FUN=function(x) 1:length(x))

您只需使用下面的代码就可以做到这一点。这将假设A矩阵是一维的,但这不是一个太大的假设

A=[1 2 3 1 1 1 2 3];
vals = unique(A);
B = zeros(size(A));
for i = 1:numel(vals)
   idxs = find(diff([0,cumsum(A == vals(i))]));
   B(idxs) = 1:numel(idxs);
end

这个解决方案是为MATLAB,而不是R。我不知道你想要哪一个。如果您想要一个R答案,我建议您选择其他人的答案:)

以下是MATLAB中的一个解决方案:

B = sum(triu(bsxfun(@eq, A, A.')));
对于Matlab:

B = sum(tril(repmat(A,length(A),1)).' + tril(repmat(NaN,length(A),length(A)),-1) == repmat(A,length(A),1))
如果
A
保证不包含零,则可简化为:

B = sum(tril(repmat(A,length(A),1)).' == repmat(A,length(A),1));

您想要总计还是运行总计?
ave(a,a,FUN=seq_along)
是我通常使用的方法。如果
a
包含零,此方法将失败。@mohsennostratinia谢谢。更正!