如何使用 if 条件和 find 命令重塑矩阵?

How to reshape a matrix using if condition and find command?

假设我有

dat_h=[1 0.12; 1 0.77; 2 0.37; 2 0.11; 3 0.44; 3 0.41; 4 0.91; 4 0.71; 5 0.51; 5 1.5]; 
dcat=1:5; 
hcat=[0.1 0.3 0.6 0.8 1.0];

我想要一个

的矩阵
nx= 
[ 2 1 1 0 0;
  2 1 0 0 0;
  2 2 0 0 0; 
  2 2 2 1 0; 
  2 2 1 1 1]

包含 dat_h 的第二列中每个值的出现次数,该值大于 hcat 的每个元素(按列),其中 nx 的行表示dcat.

我试过使用这个代码:

for i=1:length(dcat)
  for j=1:length(hcat)
    for k=1:length(dat_h)
      if i==dat_h(k,1)
        nx(i,j)=length(find(dat_h>=hcat(j)));
      else
        continue
      endif
    endfor
  endfor  
endfor

我只有nx=1.

你需要的是累积二维直方图。相关的 you just need to compute the 2D histogram using hist3 and then use cumsum to get the cumulative result. Note that filplr用于从尾到尾累加:

dcat = [dcat inf];
hcat = [hcat inf];
pkg load statistics
[obs, ~] = hist3(dat_h ,'Edges', {dcat,hcat});
nx = fliplr(cumsum(fliplr(obs),2));

您可以通过以下一行获得您想要的:

accumdim ( dat_h(:,1), dat_h(:,2) >= hcat )

如果您想了解 accumdim 的工作原理,请查看它的文档。