Vectors and Matrices
An expression table becomes a matrix when its entries are numbers with a defined row and column order. The numbers alone do not preserve the sample and gene labels. A correct calculation therefore starts with the orientation and the labels.
Read algebra and notation first. This page uses samples in rows and genes in columns. Some bioinformatics tools require the opposite orientation.
Shape is part of the definition
Section titled “Shape is part of the definition”A scalar is one number. A vector is an ordered collection of numbers. A matrix has two axes. For a matrix X with n rows and p columns, X_ij denotes the entry in row i, column j.
import numpy as np
sample_ids = ["sample_a", "sample_b", "sample_c"]gene_ids = ["gene_1", "gene_2"]expression = np.array([[2.0, 4.0], [6.0, 8.0], [10.0, 12.0]])print("Shape:", expression.shape)print("First sample:", expression[0])print("First gene:", expression[:, 0])print("Transpose shape:", expression.T.shape)assert expression.shape == (len(sample_ids), len(gene_ids))Shape: (3, 2)First sample: [2. 4.]First gene: [ 2. 6. 10.]Transpose shape: (2, 3)The transpose swaps rows and columns. It does not sort the data or repair a mismatch between labels and measurements. Transposing twice returns the original matrix.
Think of a transpose as changing the question asked by a row lookup. Before transposition, one row contains a sample’s measurements across genes. After transposition, one row contains a gene’s measurements across samples. The underlying values remain paired with the same sample and gene.
Mathematical matrix dimensions also specify which operations exist. Addition requires matching dimensions. Multiplication requires agreement between the inner dimensions. A transpose can make an operation dimensionally possible without making its biological interpretation appropriate.
Reduce an axis
Section titled “Reduce an axis”A column mean averages across samples. A row mean averages across genes. NumPy’s axis argument identifies the axis that disappears in the reduction.
gene_means = expression.mean(axis=0)sample_means = expression.mean(axis=1)centered = expression - gene_meansprint("Gene means:", gene_means)print("Sample means:", sample_means)print("Centered column means:", centered.mean(axis=0))assert np.allclose(centered.mean(axis=0), 0.0)Gene means: [6. 8.]Sample means: [ 3. 7. 11.]Centered column means: [0. 0.]Subtracting the gene means centers each column around zero. NumPy broadcasts the vector of means across the rows. That is valid because its entries correspond to columns in the same order.
The values here are invented measurements on a common scale. Centering raw RNA sequencing counts does not replace normalization or a suitable transformation.
Elementwise and matrix multiplication
Section titled “Elementwise and matrix multiplication”Multiplication with * acts on corresponding entries. Matrix multiplication with @ combines rows of the left matrix with columns of the right matrix. If A has shape (n, p) and B has shape (p, q), their product has shape (n, q).
weights = np.array([0.25, 0.75])weighted_entries = expression * weightsscores = expression @ weightsprint("Weighted entries:")print(weighted_entries)print("Scores:", scores)assert np.allclose(scores, weighted_entries.sum(axis=1))Weighted entries:[[0.5 3. ] [1.5 6. ] [2.5 9. ]]Scores: [ 3.5 7.5 11.5]The weighted score produces one number per sample. It assumes that each weight belongs to the corresponding gene. Reordering genes without reordering weights produces a different score without a shape error.
For one sample, the weighted score multiplies its first gene measurement by the first weight, then does the same for the next gene. It adds those contributions to produce one scalar. Repeating that calculation for every row gives the score vector.
With several weight vectors arranged as columns, the same matrix multiplication produces several scores per sample. Each output column then represents one chosen combination of genes. This is the same arrangement used later when PCA projects samples onto several component directions.
Matrix multiplication usually depends on order. A @ B and B @ A can have different shapes, different values, or only one valid order. Read the left matrix’s rows and the right matrix’s columns before interpreting the result.
Dimensions do not prove biological alignment
Section titled “Dimensions do not prove biological alignment”Two matrices can have compatible shapes while describing different samples. Join by identifiers and verify the order before converting a table to an array. Keep identifiers alongside the matrix when the file format permits it.
A one-dimensional NumPy array has shape (p,), so its transpose has the same shape. Use values[:, None] when an operation requires an explicit column with shape (p, 1).
For practice, exchange the two gene columns and exchange the two weights. The score should stay unchanged. Then exchange only the columns and inspect the difference.
Check your understanding
Section titled “Check your understanding”Why does subtracting the gene means center the columns rather than the rows?
The mean vector has one entry per gene. Broadcasting applies that same vector to each sample row, so each column loses its own mean. To center rows, each row would need its own mean with an explicit column dimension.
Further reading
Section titled “Further reading”-
The shape, axis, and broadcasting examples explain how array operations select dimensions. Compare these rules with centering each expression column.
-
The course includes lectures, assignments, and solutions on matrix operations and linear systems. These materials extend the weighted-score calculation to matrix transformations.
Continue with linear algebra and geometry. The NumPy guide gives more detail on array behavior.