Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Find submatrix
#include <stdio.h>
#include <stdlib.h>
//Malloc a matrix
int **malloc_matrix(size_t rows, size_t cols)
{
int **data_pointer = (int **)malloc(sizeof(int *) * rows);
for (int i = 0; i < rows; i++)
{
data_pointer[i] = malloc(sizeof(int) * cols);
}
return data_pointer;
}
//Free matrix
void free_matrix(int **data_pointer, size_t rows){
for (int i = 0; i < rows; i++)
{
free(data_pointer[i]);
}
free(data_pointer);
}
int main()
{
int **matrix;
int **submatrix;
int rows, cols, remove_row, remove_col;
printf("Input rows: ");
scanf("%d", &rows);
printf("Input column: ");
scanf("%d", &cols);
if (rows < 1 || cols < 1)
{
printf("Could not create a matrix like that.\n");
return 1;
}
matrix = malloc_matrix(rows, cols);
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
matrix[i][j] = rand() % 255;
printf("%8d", matrix[i][j]);
}
printf("\n");
}
printf("Input removing row: ");
scanf("%d", &remove_row);
printf("Input removing column: ");
scanf("%d", &remove_col);
if ((remove_row > rows || remove_row < 1) || (remove_col > cols || remove_col < 1))
{
printf("Could not remove these row and colum.");
return 2;
}
//Decrease row & col to get index
remove_row--;
remove_col--;
submatrix = malloc_matrix(rows - 1, cols - 1);
for (int i = 0, k = 0; i < rows; i++)
{
for (int j = 0, l = 0; j < cols; j++)
{
if (i != remove_row && j != remove_col)
{
submatrix[k][l] = matrix[i][j];
}
if (j != remove_col)
{
l++;
}
}
if (i != remove_row)
{
k++;
}
}
for (int i = 0; i < rows - 1; i++)
{
for (int j = 0; j < cols - 1; j++)
{
printf("%8d", submatrix[i][j]);
}
printf("\n");
}
free_matrix(matrix, rows);
free_matrix(submatrix, rows -1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.