-4

Lets say I have a specific 2d array of 100x100 like so

I'm implementing an adjacency matrix and thus I want to be able to zero a specific column and line (the same column and line in this case), zeroing lines is pretty straightforward but I'm not really able to understand how I would go about for columns.

For example to zero the 2nd element of the adjacency matrix:

enter image description here

spacing
  • 730
  • 2
  • 10
  • 41

3 Answers3

1
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;
}
RomCoo
  • 1,868
  • 2
  • 23
  • 36
0

For example you can do it the following way

for ( size_t i = 0; i < 3; i++ )
{
    a[1][i] = 0;
    a[i][1] = 0;
}

For i equal to 1 a[1][1] will be set to zero twice. However it is unimportant. If you want you can use the if statement for this case.

For example

for ( size_t i = 0; i < 3; i++ )
{
    a[1][i] = 0;
    if ( i != 1 ) a[i][1] = 0;
}

Here is a demonstrative program

#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" );
    }
}

The program output is

 3  2  5 
 6  4  2 
 1 61 45 

 3  0  5 
 0  0  0 
 1  0 45 
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

if Mat is a square matrix, simple do that:

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;    
    }
}

Just pay attention when your mat has odd/even size! when size comes even, i suppose you need to take 2 columns and 2 lines! then you should do that:

Follow this even example in this image:

enter image description here

Han Arantes
  • 775
  • 1
  • 7
  • 19