🎓 A1Learner
🔍
0 of 46 lessons completed

Zig Vector Operations

A vector operation is an operation that acts on matching lanes of vectors at the same time. One line can add four lanes at once.

Add a splat

This program adds 10 to every lane by adding a splat vector to a plain vector.

const std = @import("std");
pub fn main() !void {
    const out = std.io.getStdOut().writer();
    const v: @Vector(4, i32) = .{ 1, 2, 3, 4 };
    const ten: @Vector(4, i32) = @splat(10);
    const s = v + ten;
    try out.print("{d} {d} {d} {d}", .{ s[0], s[1], s[2], s[3] });
}

Scale every lane

This program doubles every lane by multiplying by a splat of 2.

const std = @import("std");
pub fn main() !void {
    const out = std.io.getStdOut().writer();
    const v: @Vector(4, i32) = .{ 1, 2, 3, 4 };
    const doubled = v * @as(@Vector(4, i32), @splat(2));
    try out.print("{d} {d} {d} {d}", .{ doubled[0], doubled[1], doubled[2], doubled[3] });
}

Larger and smaller lanes

This program takes the larger lane from each pair, then the smaller lane from each pair.

const std = @import("std");
pub fn main() !void {
    const out = std.io.getStdOut().writer();
    const a: @Vector(4, i32) = .{ 5, 2, 9, 1 };
    const b: @Vector(4, i32) = .{ 3, 8, 4, 7 };
    const m = @max(a, b);
    const n = @min(a, b);
    try out.print("{d} {d} {d} {d}\n", .{ m[0], m[1], m[2], m[3] });
    try out.print("{d} {d} {d} {d}", .{ n[0], n[1], n[2], n[3] });
}

Example

const std = @import("std");
pub fn main() !void {
    const out = std.io.getStdOut().writer();
    const v: @Vector(4, i32) = .{ 1, 2, 3, 4 };
    const two: @Vector(4, i32) = @splat(2);
    const ten: @Vector(4, i32) = @splat(10);
    const s = v * two + ten;
    try out.print("{d} {d} {d} {d}", .{ s[0], s[1], s[2], s[3] });
}

Key points

  • Element-wise: an element-wise operation is an operation that acts on matching lanes separately.
  • Scalar: a scalar is a single ordinary value, not a vector.
  • Splat: a splat is an operation that copies one scalar value into every lane of a vector.
  • @splat takes one value, and the vector type comes from the surrounding context.
  • An @as cast can pin down a splat vector type when context alone is not enough.
  • Adding two vectors adds matching lanes together.

The code builds a vector and two splat vectors. Multiplication doubles every lane, and addition adds 10 to every lane. Printing shows the scaled and shifted lanes in order.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does @splat(10) produce when its type is @Vector(4, i32)?