cos — Compute cosine element-wise in MATLAB and RunMat.
y = cos(x) evaluates cosine of each element in x using radian input. Real and complex values are handled element-wise with behavior aligned to MATLAB and RunMat.
Syntax
Y = cos(X)
Y = cos(X, "like", P)Inputs
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
X | Any | Yes | — | Input scalar, array, char array, complex value, or gpuArray. |
like | StringScalar | Yes | "like" | Output template selector keyword. |
P | LikePrototype | Yes | — | Prototype determining host vs gpuArray output residency. |
Returns
| Name | Type | Description |
|---|---|---|
Y | Any | Element-wise cosine result. |
Errors
| Identifier | When | Message |
|---|---|---|
RunMat:cos:InvalidInput | Input cannot be interpreted as supported numeric/logical/char/complex data. | cos: invalid input |
RunMat:cos:InvalidOption | Optional arguments after X are malformed or unsupported. | cos: invalid option |
RunMat:cos:ArgCount | Too many input arguments were supplied. | cos: too many input arguments |
RunMat:cos:LikePrototype | The "like" prototype is unsupported for this output conversion path. | cos: invalid "like" prototype |
RunMat:cos:GpuUnavailable | GPU output was requested via "like" but no active provider is available. | cos: GPU provider unavailable |
RunMat:cos:Internal | Internal tensor conversion/allocation/provider flow failed. | cos: internal error |
How cos works
- Operates on scalars, vectors, matrices, and N-D tensors with MATLAB-compatible implicit expansion.
- Logical and integer inputs are promoted to double precision before evaluation so downstream arithmetic matches MATLAB’s numeric tower.
- Complex values use the analytic extension
cos(a + bi) = cos(a)cosh(b) - i·sin(a)sinh(b)while propagatingNaN/Infcomponents independently. - Character arrays are interpreted through their Unicode code points and return dense double arrays that mirror MATLAB’s behaviour.
- Appending
'like', prototypemirrors the prototype’s class and residency (host or GPU), re-uploading the result when a device prototype is supplied. - Empty inputs and singleton dimensions are preserved without introducing extraneous allocations.
Does RunMat run cos on the GPU?
With RunMat Accelerate active, tensors remain on the device and execute through the provider’s unary_cos hook (or fused elementwise kernels) without leaving GPU memory.
If the provider declines the operation—for example, when only CPU precision is available or the operand type is unsupported—RunMat transparently gathers to the host, computes the result, and reapplies the requested residency rules (including 'like' prototypes).
Fusion planning keeps neighbouring elementwise operators grouped, reducing host↔device transfers even when an intermediate fallback occurs.
GPU memory and residency
A = reshape(0:5, [3 2]);
result = cos(A); % planner keeps the tensor on device when beneficialExpected output (after gather(result)):
result =
1.0000 -0.9899
0.5403 -0.6536
-0.4161 0.2837Examples
Cosine of zero
y = cos(0)Expected output:
y = 1Cosine of evenly spaced angles
theta = linspace(0, 2*pi, 5);
values = cos(theta)Expected output:
values = [1 0 -1 0 1]Cosine of complex data
z = cos(1 + 2i)Expected output:
z = 2.0327 - 3.0519iCosine on a GPU tensor without manual residency
A = reshape(0:5, [3 2]);
result = cos(A) % planner keeps the tensor on device when beneficialExpected output:
result =
1.0000 -0.9900
0.5403 -0.6536
-0.4161 0.2837Keeping results on the GPU with a 'like' prototype
proto = gpuArray.zeros(1, 1, 'single');
angles = [0 pi/2 pi];
deviceResult = cos(angles, 'like', proto);
result = gather(deviceResult)Expected output:
result = [1 0 -1]Matching a host prototype while inputs live on the GPU
G = gpuArray([0 1 2]);
hostLike = cos(G, 'like', zeros(1, 'double'))Expected output:
hostLike = [1 0.5403 -0.4161]Using cos with coding agents
Open a RunMat example with live inputs, then ask the agent to explain how cos changes the result.
Run a small cos example, explain the result, then change one input and compare the output.
FAQ
When should I use the cos function?⌄
Use cos whenever you need the cosine of angles expressed in radians—whether those angles are scalars, vectors, matrices, or higher-dimensional tensors.
Does cos promote inputs to double precision?⌄
Yes. Unless you request otherwise with 'like', RunMat promotes numeric inputs to double precision, matching MATLAB’s default behaviour.
How does cos handle complex inputs?⌄
Complex numbers follow MATLAB’s analytic definition cos(a + bi) = cos(a)cosh(b) - i·sin(a)sinh(b) so both the real and imaginary parts are handled correctly.
What happens if the GPU provider lacks unary_cos?⌄
RunMat gathers the tensor to the host, evaluates cosine with the CPU reference path, and then reapplies residency rules. If a 'like' prototype targets the GPU, the result is uploaded back before returning.
Can I rely on MATLAB broadcasting rules?⌄
Yes. Scalar and singleton dimensions implicitly expand just as they do in MATLAB.
Does cos work with character arrays?⌄
Yes. Character arrays are converted to their Unicode code points before cosine is evaluated, and the result is returned as a dense double array of the same size.
Related Math functions
Trigonometry
acos · acosh · asin · asinh · atan · atan2 · atanh · cosd · cosh · deg2rad · rad2deg · sin · sind · sinh · tan · tand · tanh
Elementwise
abs · angle · complex · conj · double · exp · expm1 · factorial · gamma · hypot · imag · ldivide · log · log10 · log1p · log2 · minus · nextpow2 · plus · pow2 · power · rdivide · real · sign · single · sqrt · times
Reduction
all · any · cummax · cummin · cumprod · cumsum · cumtrapz · diff · gradient · max · mean · median · min · nnz · prod · std · sum · trapz · var
Structure
Open-source implementation
Unlike proprietary runtimes, every RunMat function is open-source. Read exactly how cos is executed, line by line, in Rust.
- View the source for cos in Rust on GitHub
- Learn how the RunMat runtime works
- Found a bug? Open an issue with a minimal reproduction.
About RunMat
RunMat is an open-source runtime that executes MATLAB-syntax code blazing on any GPU. It is licensed under the Apache 2.0 license.
- RunMat automatically optimizes your math for GPU execution on Apple, Nvidia, and AMD hardware. No code changes needed. Simulations that took hours now take minutes.
- Start running code in seconds. RunMat runs in the browser, on the desktop, or from the CLI. No license server, no IT ticket.