Making a matrix from numerical ranges: Difference between revisions

From Master of Neuroscience Wiki
Created page with "== The goal == Making a new matrix… Questions to [mailto:davrot@uni-bremen.de David Rotermund] Using '''import numpy as np''' is the standard. == Simple example – new [https://numpy.org/doc/stable/reference/generated/numpy.zeros.html np.zeros()] == Define the size of your new matrix with a tuple, e.g.<syntaxhighlight lang="python">M = numpy.zeros((DIM_0, DIM_1, DIM_2, …))​</syntaxhighlight> === 1d === <syntaxhighlight lang="python">import numpy as np M = np...."
 
No edit summary
 
(One intermediate revision by the same user not shown)
Line 1: Line 1:
== The goal ==
Making a matrix from numerical ranges…
Making a new matrix…


Questions to [mailto:davrot@uni-bremen.de David Rotermund]
Questions to [mailto:davrot@uni-bremen.de David Rotermund]


Using '''import numpy as np''' is the standard.
== [https://numpy.org/doc/stable/reference/generated/numpy.arange.html numpy.arange] ==
<syntaxhighlight lang="python">numpy.arange([start, ]stop, [step, ]dtype=None, *, like=None)</syntaxhighlight><blockquote>Return evenly spaced values within a given interval.


== Simple example – new [https://numpy.org/doc/stable/reference/generated/numpy.zeros.html np.zeros()] ==
arange can be called with a varying number of positional arguments:
Define the size of your new matrix with a tuple, e.g.<syntaxhighlight lang="python">M = numpy.zeros((DIM_0, DIM_1, DIM_2, …))​</syntaxhighlight>


=== 1d ===
'''arange(stop)''': Values are generated within the half-open interval [0, stop) (in other words, the interval including start but excluding stop).
<syntaxhighlight lang="python">import numpy as np


M = np.zeros((2))
'''arange(start, stop)''': Values are generated within the half-open interval [start, stop).
print(M)</syntaxhighlight>Output:<syntaxhighlight lang="python">[0. 0.]</syntaxhighlight>


=== 2d ===
'''arange(start, stop, step)''' Values are generated within the half-open interval [start, stop), with spacing between values given by step.
<syntaxhighlight lang="python">import numpy as np


M = np.zeros((2, 3))
For integer arguments the function is roughly equivalent to the Python built-in range, but returns an ndarray rather than a range instance.
print(M)</syntaxhighlight>Output:<syntaxhighlight lang="python">[[0. 0. 0.]
[0. 0. 0.]]</syntaxhighlight>


=== 3d ===
'''When using a non-integer step, such as 0.1, it is often better to use numpy.linspace.'''</blockquote>Examples:<syntaxhighlight lang="python">import numpy as np
<syntaxhighlight lang="python">import numpy as np


M = np.zeros((2, 3, 4))
print(np.arange(5)) # -> [0 1 2 3 4]
print(M)</syntaxhighlight>Output:<syntaxhighlight lang="python">[[[0. 0. 0. 0.]
print(np.arange(0, 5)) # -> [0 1 2 3 4]
  [0. 0. 0. 0.]
print(np.arange(2, 5)) # -> [2 3 4]
  [0. 0. 0. 0.]]
print(np.arange(0, 5, 2)) # -> [0 2 4]</syntaxhighlight>It can be nicely combined with '''reshape()''':<syntaxhighlight lang="python">import numpy as np
print(np.arange(0, 9).reshape(3, 3))</syntaxhighlight>Output:<syntaxhighlight lang="python">[[0 1 2]
[3 4 5]
[6 7 8]]</syntaxhighlight>'''Do not use it with non-integer values for step!!!''' This can happen and you don’t want this to happen:<syntaxhighlight lang="python">import numpy as np


[[0. 0. 0. 0.]
print(np.arange(-3, 0, 0.5, dtype=int)) # -> [-3 -2 -1  0 1  2]</syntaxhighlight>
  [0. 0. 0. 0.]
  [0. 0. 0. 0.]]]</syntaxhighlight>


== Simple example – recycle [https://numpy.org/doc/stable/reference/generated/numpy.zeros_like.html np.zeros_like()] ==
== [https://numpy.org/doc/stable/reference/generated/numpy.linspace.html numpy.linspace] ==
If you have a matrix with the same size ​you want then you can use zeros_like. This will also copy other properties like the data type.
<syntaxhighlight lang="python">numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0)</syntaxhighlight><blockquote>Return evenly spaced numbers over a specified interval.


as a prototype use
Returns num evenly spaced samples, calculated over the interval [start, stop].


N = numpy.zeros_like(M)<syntaxhighlight lang="python">import numpy as np
The endpoint of the interval can optionally be excluded.</blockquote><blockquote>'''start''': array_like


M = np.zeros((2, 3, 4))
The starting value of the sequence.</blockquote><blockquote>'''stop''': array_like


N = np.zeros_like(M)
The end value of the sequence, unless endpoint is set to False. In that case, the sequence consists of all but the last of num + 1 evenly spaced samples, so that stop is excluded. Note that the step size changes when endpoint is False.</blockquote><blockquote>'''num''': int, optional
print(N)</syntaxhighlight>Output:<syntaxhighlight lang="python">[[[0. 0. 0. 0.]
  [0. 0. 0. 0.]
  [0. 0. 0. 0.]]


[[0. 0. 0. 0.]
Number of samples to generate. Default is 50. Must be non-negative.</blockquote><blockquote>'''endpoint''': bool, optional
  [0. 0. 0. 0.]
  [0. 0. 0. 0.]]]</syntaxhighlight>


== Remember unpacking ==
If True, stop is the last sample. Otherwise, it is not included. Default is True.</blockquote>An example:<syntaxhighlight lang="python">import numpy as np
{: .topic-optional} This is an optional topic!<syntaxhighlight lang="python">import numpy as np


d = (3, 4)
print(np.linspace(0, 1, num=10, endpoint=False))  # -> [0.  0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9]
M = np.zeros((2, *d))
print(np.arange(0, 10) / 10)  # -> [0.  0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9]</syntaxhighlight>Be mindful concerning the endpoint setting ('''Notice the … 8 10]'''):<syntaxhighlight lang="python">import numpy as np


print(M)</syntaxhighlight>
print(np.linspace(0, 10, num=10, endpoint=False, dtype=int))  # -> [0 1 2 3 4 5 6 7 8 9]
print(np.linspace(0, 10, num=10, endpoint=True, dtype=int))  # -> [ 0  1  2  3  4  5  6  7  8 10]</syntaxhighlight>


== np.empty is not np.zeros ==
== [https://numpy.org/doc/stable/reference/generated/numpy.logspace.html numpy.logspace] ==
If you are sure that you don’t care about what is inside the matrix in the beginning use<syntaxhighlight lang="python">M = numpy.empty((DIM_0, DIM_1, DIM_2,...))</syntaxhighlight>Empty claims a region in the memory and uses it for a matrix. Zeros goes one step further. It fills the memory with zeros.
<syntaxhighlight lang="python">numpy.logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None, axis=0)</syntaxhighlight><blockquote>Return numbers spaced evenly on a log scale.


Thus random junk​ (i.e. data that was stored prior at that memory position) with be the content of a matrix if you use empty. However, np.empty() is faster than np.zeros().<syntaxhighlight lang="python">​import numpy as np
In linear space, the sequence starts at base ** start (base to the power of start) and ends with base ** stop (see endpoint below).</blockquote>
M = np.empty((10, 4))
print(M)</syntaxhighlight><syntaxhighlight lang="python">[[1.66706425e-316 0.00000000e+000 6.89933729e-310 6.89933730e-310]
[6.89933729e-310 6.89933730e-310 6.89933729e-310 6.89933730e-310]
[6.89933730e-310 6.89933730e-310 6.89933729e-310 6.89933729e-310]
[6.89933730e-310 6.89933729e-310 6.89933730e-310 6.89933729e-310]
[6.89933730e-310 4.30513389e-317 4.30321296e-317 6.89933825e-310]
[4.30389280e-317 6.89933822e-310 4.30366750e-317 6.89933822e-310]
[4.30311810e-317 4.30480583e-317 4.30462401e-317 4.30336316e-317]
[6.89933822e-310 4.30386513e-317 4.30358055e-317 4.30571886e-317]
[4.30568724e-317 4.30659237e-317 6.89933822e-310 6.89933822e-310]
[6.89933822e-310 6.89933822e-310 4.30289676e-317 6.89920336e-310]]</syntaxhighlight>
 
== [https://numpy.org/doc/stable/reference/routines.array-creation.html#from-shape-or-value From shape or value] ==
{| class="wikitable"
|[https://numpy.org/doc/stable/reference/generated/numpy.empty.html#numpy.empty empty](shape[, dtype, order, like])
|Return a new array of given shape and type, without initializing entries.
|-
|[https://numpy.org/doc/stable/reference/generated/numpy.empty_like.html#numpy.empty_like empty_like](prototype[, dtype, order, subok, …])
|Return a new array with the same shape and type as a given array.
|-
|[https://numpy.org/doc/stable/reference/generated/numpy.eye.html#numpy.eye eye](N[, M, k, dtype, order, like])
|Return a 2-D array with ones on the diagonal and zeros elsewhere.
|-
|[https://numpy.org/doc/stable/reference/generated/numpy.identity.html#numpy.identity identity](n[, dtype, like])
|Return the identity array.
|-
|[https://numpy.org/doc/stable/reference/generated/numpy.ones.html#numpy.ones ones](shape[, dtype, order, like])
|Return a new array of given shape and type, filled with ones.
|-
|[https://numpy.org/doc/stable/reference/generated/numpy.ones_like.html#numpy.ones_like ones_like](a[, dtype, order, subok, shape])
|Return an array of ones with the same shape and type as a given array.
|-
|[https://numpy.org/doc/stable/reference/generated/numpy.zeros.html#numpy.zeros zeros](shape[, dtype, order, like])
|Return a new array of given shape and type, filled with zeros.
|-
|[https://numpy.org/doc/stable/reference/generated/numpy.zeros_like.html#numpy.zeros_like zeros_like](a[, dtype, order, subok, shape])
|Return an array of zeros with the same shape and type as a given array.
|-
|[https://numpy.org/doc/stable/reference/generated/numpy.full.html#numpy.full full](shape, fill_value[, dtype, order, like])
|Return a new array of given shape and type, filled with fill_value.
|-
|[https://numpy.org/doc/stable/reference/generated/numpy.full_like.html#numpy.full_like full_like](a, fill_value[, dtype, order, …])
|Return a full array with the same shape and type as a given array.
|}

Latest revision as of 14:18, 23 October 2025

Making a matrix from numerical ranges…

Questions to David Rotermund

numpy.arange

numpy.arange([start, ]stop, [step, ]dtype=None, *, like=None)

Return evenly spaced values within a given interval.

arange can be called with a varying number of positional arguments:

arange(stop): Values are generated within the half-open interval [0, stop) (in other words, the interval including start but excluding stop).

arange(start, stop): Values are generated within the half-open interval [start, stop).

arange(start, stop, step) Values are generated within the half-open interval [start, stop), with spacing between values given by step.

For integer arguments the function is roughly equivalent to the Python built-in range, but returns an ndarray rather than a range instance.

When using a non-integer step, such as 0.1, it is often better to use numpy.linspace.

Examples:

import numpy as np

print(np.arange(5)) # -> [0 1 2 3 4]
print(np.arange(0, 5)) # -> [0 1 2 3 4]
print(np.arange(2, 5)) # -> [2 3 4]
print(np.arange(0, 5, 2)) # -> [0 2 4]

It can be nicely combined with reshape():

import numpy as np
print(np.arange(0, 9).reshape(3, 3))

Output:

[[0 1 2]
 [3 4 5]
 [6 7 8]]

Do not use it with non-integer values for step!!! This can happen and you don’t want this to happen:

import numpy as np

print(np.arange(-3, 0, 0.5, dtype=int)) # -> [-3 -2 -1  0  1  2]

numpy.linspace

numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0)

Return evenly spaced numbers over a specified interval.

Returns num evenly spaced samples, calculated over the interval [start, stop].

The endpoint of the interval can optionally be excluded.

start: array_like The starting value of the sequence.

stop: array_like The end value of the sequence, unless endpoint is set to False. In that case, the sequence consists of all but the last of num + 1 evenly spaced samples, so that stop is excluded. Note that the step size changes when endpoint is False.

num: int, optional Number of samples to generate. Default is 50. Must be non-negative.

endpoint: bool, optional If True, stop is the last sample. Otherwise, it is not included. Default is True.

An example:

import numpy as np

print(np.linspace(0, 1, num=10, endpoint=False))  # -> [0.  0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9]
print(np.arange(0, 10) / 10)  # -> [0.  0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9]

Be mindful concerning the endpoint setting (Notice the … 8 10]):

import numpy as np

print(np.linspace(0, 10, num=10, endpoint=False, dtype=int))  # -> [0 1 2 3 4 5 6 7 8 9]
print(np.linspace(0, 10, num=10, endpoint=True, dtype=int))  # -> [ 0  1  2  3  4  5  6  7  8 10]

numpy.logspace

numpy.logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None, axis=0)

Return numbers spaced evenly on a log scale. In linear space, the sequence starts at base ** start (base to the power of start) and ends with base ** stop (see endpoint below).