在尽可能少的循环中动态附加数据

时间:2021-12-25 21:15:49

I have a matrix A=(n,m) and I need to scan its columns one by one and if the sum of the elements of a column is greater than a threshold, put the column into a new matrix B=(n,?).

我有一个矩阵A =(n,m),我需要逐个扫描它的列,如果列的元素总和大于阈值,则将列放入一个新的矩阵B =(n,? )。

A=[1 2 3
   3 1 1
   4 2 8]

threshold=6

And as result:

结果如下:

B=[1 3
   3 1
   4 8]

Obviously, i do not know how many columns in B, therefore in a first loop, I check the sum of elements in a column, then if the value is greater than the threshold I repeat the loop for appending the column in B by a realloc.

显然,我不知道B中有多少列,因此在第一个循环中,我检查列中元素的总和,然后如果该值大于阈值,则重复循环以通过realloc将列附加到B中。

okcol=0;
double *B = malloc(n*sizeof(double));
for (col=0;col<m;col++){
  sum=0;
  for (row=0;row<n;row++){
    sum+=A[row+col*n];
    if(sum>threshold){
      B = realloc(B, (okcol+1)*n*sizeof(double));
      for (row2=0;row2<n;row2++){
        B [okcol*n+row2] = A[row2+col*n];
      }
      okcol++;
    }  
  }
}          

Is there a method for automatically append the elements in B and "delete" them if the sum is less than threshold? In other words I would like to avoid the last loop.

是否有一种方法可以自动将元素附加到B中,如果总和小于阈值,则“删除”它们?换句话说,我想避免最后一个循环。

2 个解决方案

#1


0  

You could use a linked list, so every time you just add an element (in this case the index of every column that meets the threshold) and at the end of the cycles you know how much memory you have to allocate to put in the columns into a simple 2 dimensional array.

您可以使用链接列表,因此每次只添加一个元素(在这种情况下是满足阈值的每列的索引),并且在周期结束时,您知道必须分配多少内存以放入列中成一个简单的二维数组。

You would at least a lot of reallocations in this way.

你至少会以这种方式进行大量的重新分配。

#2


0  

double *B = (double*)malloc(n*m*sizeof(double));
int c,r,okcol=0;
for(c=0;c<m;++c){
    for(sum=0, r=0;r<n;++r){
        sum+=(B[r+okcol*m]=A[r+c*m]);
    }
    if(sum > threshold)
        ++okcol;
}
B=(double*)realloc(B, okcol*m*sizeof(double));

#1


0  

You could use a linked list, so every time you just add an element (in this case the index of every column that meets the threshold) and at the end of the cycles you know how much memory you have to allocate to put in the columns into a simple 2 dimensional array.

您可以使用链接列表,因此每次只添加一个元素(在这种情况下是满足阈值的每列的索引),并且在周期结束时,您知道必须分配多少内存以放入列中成一个简单的二维数组。

You would at least a lot of reallocations in this way.

你至少会以这种方式进行大量的重新分配。

#2


0  

double *B = (double*)malloc(n*m*sizeof(double));
int c,r,okcol=0;
for(c=0;c<m;++c){
    for(sum=0, r=0;r<n;++r){
        sum+=(B[r+okcol*m]=A[r+c*m]);
    }
    if(sum > threshold)
        ++okcol;
}
B=(double*)realloc(B, okcol*m*sizeof(double));