scalar2ndarrayLike

Convert a scalar value to a zero-dimensional ndarray having the same data type as a provided ndarray.

Usage

var scalar2ndarrayLike = require( '@stdlib/ndarray/base/from-scalar-like' );

scalar2ndarrayLike( x, value )

Returns a zero-dimensional ndarray containing a provided scalar value and having the same data type as a provided ndarray.

var zeros = require( '@stdlib/ndarray/base/zeros' );

var x = zeros( 'float32', [ 2, 2 ], 'row-major' );
// returns <ndarray>

var y = scalar2ndarrayLike( x, 1.0 );
// returns <ndarray>

var sh = y.shape;
// returns []

var dt = y.dtype;
// returns 'float32'

var v = y.get();
// returns 1.0

Notes

  • Along with data type and order, the function infers the "class" of the returned ndarray from the provided ndarray. For example, if provided a "base" ndarray, the function returns a base ndarray. If provided a non-base ndarray, the function returns a non-base ndarray.
  • If value is a number and a provided ndarray has a complex data type, the function returns a zero-dimensional ndarray containing a complex number whose real component equals the provided scalar value and whose imaginary component is zero.

Examples

var dtypes = require( '@stdlib/ndarray/dtypes' );
var empty = require( '@stdlib/ndarray/base/empty' );
var scalar2ndarrayLike = require( '@stdlib/ndarray/base/from-scalar-like' );

// Get a list of data types:
var dt = dtypes();

// Generate zero-dimensional arrays...
var x;
var y;
var i;
for ( i = 0; i < dt.length; i++ ) {
    x = empty( dt[ i ], [ 2, 2 ], 'row-major' );
    y = scalar2ndarrayLike( x, i );
    console.log( y.get() );
}
Did you find this page helpful?