Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
189 views
in Technique[技术] by (71.8m points)

c - how to print a matrix with a negated row more efficiently

I wrote the following function:

void negate_row(const int n, const int r, int *a)
{
    if (r == 0)
    {
        printf("Matrix with negated row: ");
        printf("
");
        for (int y = 0; y < 3; y++)
        {
            *(a + 3 * r + y) = *(a + 3 * r + y) *(-1);
            printf("%d ", *(a + 3 * r + y));
        }
        printf("
");

        for (int y = 0; y < 3; y++)
        {
            *(a + 3 * r + y) = *(a + 3 * r + y) *(-1);
            printf("%d ", *(a + 3 * (r + 1) + y));
        }
        printf("
");

        for (int y = 0; y < 3; y++)
        {
            *(a + 3 * r + y) = *(a + 3 * r + y) *(-1);
            printf("%d ", *(a + 3 * (r + 2) + y));
        }
        printf("
");
    }

So basically what happens here is my function takes in a n X 3 matrix and negates a specific row using pointer arithmetic. I have been able to achieve that, I've also been able to figure out how to print that same matrix with the negated row. It's just the way I'm doing it is not efficient at all. I'd have to write an if statement for each row, ex if r == 0,1,2,3,4 etc... is there any way I can do this more efficiently?

Some clarifications: const int n decides the size of the matrix (n x 3), const int r decides what row is negated (0 <= r < n).

question from:https://stackoverflow.com/questions/66067240/how-to-print-a-matrix-with-a-negated-row-more-efficiently

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

A second loop will help. I generally find pointer code a bit harder to read. Particularly with Matrix manipulation you might be better off using array syntax instead of pointer syntax.

for (int y = 0; y < 3; y++)
{
    for (int x = 0; x < 3; x++)
    {
        printf("%d ", *(a + 3 * (r + x) + y));
    }

    printf("
");
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...