cos — Compute cosine element-wise in MATLAB and RunMat.
y = cos(x) evaluates cosine element-wise in radians. MATLAB documents single and double real or complex arrays; RunMat mode additionally admits typed integers, logicals, characters, and the "like" output form through explicit compatibility gates.
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.
- Single real and complex inputs preserve single output; double inputs preserve double output.
- Typed integers are a RunMat-only extension. All eight real integer classes are accepted only through the integer gate, must be exactly representable at the binary64 transcendental boundary, and produce double output; representability is tested from significant bits, so aligned values above
flintmaxcan remain exact. - Logical and character inputs are separate RunMat-only extensions and produce double output.
- Complex values use the analytic extension
cos(a + bi) = cos(a)cosh(b) - i·sin(a)sinh(b)while propagatingNaN/Infcomponents independently. - Appending
'like', prototypeis a RunMat-only extension that controls host/GPU residency and real/complex representation; a GPU result is transferred or recomputed onto the prototype's owning provider, and the form is not part of MATLAB's documentedcossyntax. - Empty inputs and singleton dimensions are preserved without introducing extraneous allocations.
- Table, timetable, tall, and distributed container inputs remain general RunMat container/runtime gaps rather than integer-storage gaps.
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?⌄
Single and double floating inputs preserve their class. RunMat-only integer, logical, and character inputs return double.
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?⌄
Only in RunMat compatibility mode. Character arrays are converted to Unicode code points and return a shape-preserving dense double array.
Related Math functions
Trigonometry
acos · acosh · asin · asinh · atan · atan2 · atanh · cosd · cosh · cospi · deg2rad · pol2cart · rad2deg · sin · sind · sinh · sinpi · tan · tand · tanh
Elementwise
abs · angle · bsxfun · complex · conj · double · erf · erfcinv · exp · expm1 · factorial · flintmax · gamma · gammaln · heaviside · hypot · idivide · imag · intmax · intmin · ldivide · log · log10 · log1p · log2 · minus · nextpow2 · plus · pow2 · power · rdivide · real · realmax · realmin · realsqrt · rescale · sign · single · sqrt · swapbytes · times · typecast · uint16 · uint32 · uint8
Reduction
all · any · bounds · cummax · cummin · cumprod · cumsum · cumtrapz · diff · gradient · max · maxk · mean · median · min · mink · movmax · movmean · movmedian · movmin · movprod · movstd · movsum · movvar · nnz · prod · rms · std · sum · trapz · var
Structure
bandwidth · isdiag · ishermitian · issymmetric · istril · istriu · symrcm
Signal
blackman · butter · buttord · cheb2ord · conv · conv2 · deconv · downsample · envelope · filter · filtfilt · fir1 · freqz · gauspuls · hamming · hann · hilbert · periodogram · pulstran · pwelch · rectpuls · resample · sawtooth · sinc · spectrogram · square · tripuls · unwrap · upsample · zplane
Optim
coneprog · fminbnd · fminunc · fsolve · fzero · integral · linprog · lsqcurvefit · lsqnonlin · optimoptions · optimset · quad · secondordercone
Ops
cross · ctranspose · dot · mldivide · mpower · mrdivide · mtimes · pagemtimes · pagetranspose · trace · transpose
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.