function ncols
ncols(x: array | matrix): number

Returns the number of columns in an array or matrix.

Returns the number of columns in a 1D array (treated as a row vector) or a 2D matrix.

Examples

Row vector

import { assertEquals, assertThrows } from "jsr:@std/assert";

assertEquals(ncols([5, 6, 7]), 3); // 3

Matrix with multiple rows

import { assertEquals, assertThrows } from "jsr:@std/assert";

assertEquals(ncols([[3, 2, 7], [4, 5, 6]]), 3); // 3

Single element array

import { assertEquals, assertThrows } from "jsr:@std/assert";

assertEquals(ncols([5]), 1); // 1

Single element matrix (1x1)

import { assertEquals, assertThrows } from "jsr:@std/assert";

assertEquals(ncols([[5]]), 1); // 1

Empty array (treated as 1D)

import { assertEquals, assertThrows } from "jsr:@std/assert";

assertEquals(ncols([]), 0); // 0

Empty matrix (array of empty arrays)

import { assertEquals, assertThrows } from "jsr:@std/assert";

assertEquals(ncols([[]]), 0); // 0

Non-array input (should throw an error)

import { assertEquals, assertThrows } from "jsr:@std/assert";

assertThrows(() => { ncols(5 as unknown as number[]) }, Error, 'Input must be an array or matrix');

2D matrix with a single row

import { assertEquals, assertThrows } from "jsr:@std/assert";

assertEquals(ncols([[1, 2, 3, 4]]), 4); // 4

2D matrix with varying row lengths (should throw an error)

import { assertEquals, assertThrows } from "jsr:@std/assert";

assertThrows(() => { ncols([[1, 2], [3, 4, 5]]) }, Error, 'Input must be an array or matrix');

Multi-dimensional array (should be treated as a 2D matrix)

import { assertEquals, assertThrows } from "jsr:@std/assert";

assertEquals(ncols([[1, 2], [3, 4]]), 2); // 2

Parameters

Array or matrix of elements.

Return Type

number

The number of columns in the input.

Throws

Throws an error if no input is provided or if the input is not an array.