Skip to Content
Course content

231: Practice Exercise: Matrix Multiplication in C

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Think about matrix multiplication not as a math problem, but as a way of combining two different sets of data to find a total. Imagine you're running a small bakery. You have a list of three different cakes you bake, and for each cake, you know exactly how many grams of flour, sugar, and butter it needs. That's your first matrix: Cakes × Ingredients.

Now, imagine you have two different suppliers. Supplier A sells flour, sugar, and butter at one set of prices, and Supplier B sells them at another. That's your second matrix: Ingredients × Suppliers.

If you want to know the total cost to make each cake depending on which supplier you use, you don't just multiply the numbers in the same positions. Instead, for "Cake 1" and "Supplier A," you take the flour needed and multiply it by Supplier A's flour price, then add the sugar needed times Supplier A's sugar price, and so on. You're essentially "sliding" a row from the first matrix across a column of the second.

The "Row-meets-Column" Dance

In C, this "sliding" is where most people get tangled. To get one single value in your result matrix, you need to perform a dot product. If you're looking for the value at result[i][j], you are combining the i-th row of the first matrix with the j-th column of the second.

I've seen a lot of students try to do this with just two loops. It's impossible. You need three. Two to keep track of which row and column of the result matrix you're currently filling, and a third one—the "bridge" loop—to move across the row of the first matrix and down the column of the second simultaneously.

// The core logic looks like this:
for (int i = 0; i < rowsA; i++) {
    for (int j = 0; j < colsB; j++) {
        result[i][j] = 0; // Always zero this out first!
        for (int k = 0; k < colsA; k++) {
            result[i][j] += matrixA[i][k] * matrixB[k][j];
        }
    }
}

Navigating the Triple Loop

Let's break down those indices, because i, j, k can start to look like alphabet soup if you aren't careful. i is your anchor for the first matrix (the rows). j is your anchor for the second matrix (the columns). But k is the magic worker. Notice how k is the column index for A and the row index for B? That's how the "sliding" happens. As k increments, you move right in A and down in B.

I'll give you a pro tip: always initialize your result matrix to zero. Since we're using += to accumulate the sum of the products, any garbage values left in your memory from previous allocations will wreck your calculations.

The Dimension Deal-breaker

Before you even start those loops, you have to check if the multiplication is even legal. In the bakery analogy, if you have 3 ingredients listed for your cakes, but your supplier only provides prices for 2 of them, you're stuck. You can't finish the calculation.

In C terms: the number of columns in Matrix A must equal the number of rows in Matrix B. If colsA != rowsB, you should stop immediately and return an error. If you try to run the loop anyway, you'll be reading memory you don't own, and segfault will be your only reward.




📋 Practical Task

Build a Weighted Grade Calculator

Write a C program that uses matrix multiplication to calculate the final grades for a set of students. You will need to implement the following:

  • Matrix A (Students × Assignments): Create a 3x4 matrix where each row represents a student and each column represents a score on four different assignments (e.g., Quiz 1, Quiz 2, Midterm, Final).
  • Matrix B (Assignments × Weights): Create a 4x1 matrix where each row is the weight of that specific assignment (e.g., 0.10, 0.10, 0.30, 0.50).
  • The Logic: Implement the triple-nested loop structure to multiply these matrices. The result should be a 3x1 matrix containing the final weighted grade for each of the three students.
  • Validation: Include a check to ensure the number of columns in the grade matrix matches the number of rows in the weight matrix before proceeding.

Print the final resulting matrix clearly, showing which student earned which final grade.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.