3

0我有矩阵-

A=[1 2 2 3 5 5;
   1 5 5 8 8 7;
   2 9 9 3 3 5];

从矩阵中我现在需要计算许多非零元素,给定矩阵“A”的每一行中有多少个 1、多少个 2 和多少个 3。为此,我编写了一个代码,例如:

    [Ar Ac]=size(A);

    for j=1:Ar 
        for k=1:Ac
            count(:,j)=nnz(A(j,:));
            d(:,j)=sum(A(j,:)== 1); 
            e(:,j)=sum(A(j,:)==2);  
            f(:,j)=sum(A(j,:)==3);          
    end
end

但我需要使用 on 循环编写这些,即在这里我手动使用 sum(A(j,:)== 1),sum(A(j,:)== 2) 和 sum(A(j,:)== 3) 但是有什么选项我只能写 sum(A(j,:)== 1:3) 并将所有值存储在不同的行中,即结果将是 -

b=[1 2 1;
   1 0 0;
   0 1 2];

Matlab 专家需要您的宝贵建议

4

6 回答 6

8

听起来您正在寻找直方图计数:

U = unique(A);
counts = histc(A', U)';
b = counts(:, ismember(U, [1 2 3]));

例子

%// Input matrix and vector of values to count
A = [1 2 2 3 5 5; 1 5 5 8 8 7; 2 9 9 3 3 5];
vals = [1 2 3];

%// Count values
U = unique(A);
counts = histc(A', U)';
b = counts(:, ismember(U, vals));

结果是:

b =
   1   2   1
   1   0   0
   0   1   2
于 2013-08-14T10:56:41.593 回答
3

根据询问者的要求,概括所寻求的值:

values = [ 1 2 3 ]; % or whichever values are sought
B = squeeze(sum(bsxfun(@(x,y) sum(x==y,2), A, shiftdim(values,-1)),2));
于 2013-08-14T10:56:49.107 回答
2

Here is a simple and general way. Just change n to however high you want to count. n=max(A(:)) is probably a good general value.

 result = [];
   n = 3;
   for col= 1:n
       result = [result, sum(A==col, 2)];
   end
   result

e.g. for n = 10

result =

   1   2   1   0   2   0   0   0   0   0
   1   0   0   0   2   0   1   2   0   0
   0   1   2   0   1   0   0   0   2   0
于 2013-08-14T10:52:05.530 回答
1

I'd do this way:

B = [arrayfun(@(i) find(A(i,:) == 1) , 1:3 , 'UniformOutput', false)',arrayfun(@(i) find(A(i,:) == 2) , 1:3 , 'UniformOutput', false)',arrayfun(@(i) find(A(i,:) == 3) , 1:3 , 'UniformOutput', false)'];

res = cellfun(@numel, B);
于 2013-08-14T10:51:19.193 回答
1

为什么不使用这个?

B=[];
for x=1:size(A,1)
B=[B;sum(A(x,:)==1),sum(A(x,:)==2),sum(A(x,:)==3)];
end
于 2013-08-14T10:44:39.430 回答
0

这是一个紧凑的:

sum(bsxfun(@eq, permute(A, [1 3 2]), 1:3),3)

您可以替换1:3为任何数组。你可以为它创建一个匿名函数

rowcnt = @(M, R) sum(bsxfun(@eq, permute(M, [1 3 2]), R),3);

然后在您的数据返回上运行它

>> rowcnt(A,1:3)

ans =

     1     2     1
     1     0     0
     0     1     2

对于更普遍的情况

>> rowcnt(A,[1 2 5 8])

ans =

     1     2     2     0
     1     0     2     2
     0     1     1     0
于 2013-08-14T10:58:02.943 回答