如何将二维数组的特定列归零
How to zero specific column of 2d array
假设我有一个特定的 100x100 二维数组,就像这样
我正在实现一个邻接矩阵,因此我希望能够将特定的列和行归零(在本例中为同一列和行),将行归零非常简单,但我真的不能了解我将如何处理专栏。
例如将邻接矩阵的第二个元素归零:
int column=1; //in your example
int row=1;//in your example
//for rows
for(int i = 0; i<numberofrows; i++)
{
array[i][column]=0;
}
//for columns
for(int i = 0; i<numberofcolumns; i++)
{
array[row][i]=0;
}
例如你可以按以下方式进行
for ( size_t i = 0; i < 3; i++ )
{
a[1][i] = 0;
a[i][1] = 0;
}
对于i
等于1
a[1][1]
会被置零两次。不过这并不重要。如果你愿意,你可以在这种情况下使用 if 语句。
例如
for ( size_t i = 0; i < 3; i++ )
{
a[1][i] = 0;
if ( i != 1 ) a[i][1] = 0;
}
这是一个演示程序
#include <stdio.h>
#define N1 3
int main( void )
{
int a[N1][N1] =
{
{ 3, 2, 5 },
{ 6, 4, 2 },
{ 1, 61, 45 }
};
for ( size_t i = 0; i < N1; i++ )
{
for ( size_t j = 0; j < N1; j++ ) printf( "%2d ", a[i][j] );
printf( "\n" );
}
size_t row = 1;
size_t col = 1;
for ( size_t i = 0; i < N1; i++ )
{
a[row][i] = 0;
a[i][col] = 0;
}
printf( "\n" );
for ( size_t i = 0; i < N1; i++ )
{
for ( size_t j = 0; j < N1; j++ ) printf( "%2d ", a[i][j] );
printf( "\n" );
}
}
程序输出为
3 2 5
6 4 2
1 61 45
3 0 5
0 0 0
1 0 45
如果 Mat 是方阵,那么简单:
k= (cols_of_mat)/2;
for(int i = 0; i<k; i++){
mat[k][i] = 0;
mat[i][k] = 0;
//if Mat can have even size
if(k%2==0){
mat[k-1][i] = 0;
mat[i][k-1] = 0;
}
}
当您的垫子有 odd/even 尺寸时请注意!当大小均匀时,我想你需要 2 列和 2 行!那么你应该这样做:
按照这张图片中的偶数示例:
假设我有一个特定的 100x100 二维数组,就像这样
我正在实现一个邻接矩阵,因此我希望能够将特定的列和行归零(在本例中为同一列和行),将行归零非常简单,但我真的不能了解我将如何处理专栏。
例如将邻接矩阵的第二个元素归零:
int column=1; //in your example
int row=1;//in your example
//for rows
for(int i = 0; i<numberofrows; i++)
{
array[i][column]=0;
}
//for columns
for(int i = 0; i<numberofcolumns; i++)
{
array[row][i]=0;
}
例如你可以按以下方式进行
for ( size_t i = 0; i < 3; i++ )
{
a[1][i] = 0;
a[i][1] = 0;
}
对于i
等于1
a[1][1]
会被置零两次。不过这并不重要。如果你愿意,你可以在这种情况下使用 if 语句。
例如
for ( size_t i = 0; i < 3; i++ )
{
a[1][i] = 0;
if ( i != 1 ) a[i][1] = 0;
}
这是一个演示程序
#include <stdio.h>
#define N1 3
int main( void )
{
int a[N1][N1] =
{
{ 3, 2, 5 },
{ 6, 4, 2 },
{ 1, 61, 45 }
};
for ( size_t i = 0; i < N1; i++ )
{
for ( size_t j = 0; j < N1; j++ ) printf( "%2d ", a[i][j] );
printf( "\n" );
}
size_t row = 1;
size_t col = 1;
for ( size_t i = 0; i < N1; i++ )
{
a[row][i] = 0;
a[i][col] = 0;
}
printf( "\n" );
for ( size_t i = 0; i < N1; i++ )
{
for ( size_t j = 0; j < N1; j++ ) printf( "%2d ", a[i][j] );
printf( "\n" );
}
}
程序输出为
3 2 5
6 4 2
1 61 45
3 0 5
0 0 0
1 0 45
如果 Mat 是方阵,那么简单:
k= (cols_of_mat)/2;
for(int i = 0; i<k; i++){
mat[k][i] = 0;
mat[i][k] = 0;
//if Mat can have even size
if(k%2==0){
mat[k-1][i] = 0;
mat[i][k-1] = 0;
}
}
当您的垫子有 odd/even 尺寸时请注意!当大小均匀时,我想你需要 2 列和 2 行!那么你应该这样做:
按照这张图片中的偶数示例: