I have a for loop (100 passes) which generates a numpy array during each pass. Is there a way to add these 100 arrays (element wise) and then calculate the array which represents the average of these 100 arrays?
Perhaps you're looking for:
np.mean(arr, axis=0)
Alternatively, you can do:
np.sum(arr, axis=0) / len(arr)
Here, arr is the array you created with the loop.
You can define arr as:
arr = []
for i in range(100):
# create numpy array here and assign it to x
arr.append(x)
Then you can do np.mean etc on arr.
Related
enter image description here
I am getting odd behavior with Jupyter/Numpy/Tranpose()/1D Arrays.
I found another post where transpose() will not transpose a 1D array, but in previous Jupyter notebooks, it does.
I have an example where it is inconsistent, and I do not understand:
Please see the picture attached of my jupyter notebook if 2 more or less identical arrays with 2 different outputs.
It seems it IS and IS NOT transposing the 1D array. Inconsistency is bad
outputs is (1000,) and (1,1000), why does this occur?
# GENERATE WAVEORM:
#---------------------------------------------------------------------------------------------------
N = 1000
fxc = []
fxn = []
for t in range(0,N):
fxc.append(A1*m.sin(2.0*pi*50.0*dt*t) + A2*m.sin(2.0*pi*120.0*dt*t))
fxn.append(A1*m.sin(2.0*pi*50.0*dt*t) + A2*m.sin(2.0*pi*120.0*dt*t) + 5*np.random.normal(u,std,size=1))
#---------------------------------------------------------------------------------------------------
# TAKE TRANSPOSE:
#---------------------------------
fc = np.transpose(np.array(fxc))
fn = np.transpose(np.array(fxn))
#---------------------------------
# PRINT DIMENSION:
#---------------------------------
print(fc.shape)
print(fn.shape)
#---------------------------------
Remove size=1 from your call to numpy.random.normal. Then it will return a scalar instead of a 1-d array of length 1.
For example,
In [2]: np.random.normal(0, 3, size=1)
Out[2]: array([0.47058288])
In [3]: np.random.normal(0, 3)
Out[3]: 4.350733438283539
Using size=1 in your code is a problem, because it results in fxn being a list of 1-d arrays (e.g. something like [[0.123], [-.4123], [0.9455], ...]. When NumPy converts that to an array, it has shape (N, 1). Transposing such an array results in the shape (1, N).
fxc, on the other hand, is a list of scalars (e.g. something like [0.123, 0.456, ...]). When converted to a NumPy array, it will be a 1-d array with shape (N,). NumPy's transpose operation swaps dimensions, but it does not create new dimensions, so transposing a 1-d array does nothing.
I am new to Swift and am struggling to work out how to determine the size of a multidimensional array.
I can use the count function for single arrays, however when i create a matrix/multidimensional array, the output for the count call just gives a single value.
var a = [[1,2,3],[3,4,5]]
var c: Int
c = a.count
print(c)
2
The above matrix 'a' clearly has 2 rows and 3 columns, is there any way to output this correct size.
In Matlab this is a simple task with the following line of code,
a = [1,2,3;3,4,5]
size(a)
ans =
2 3
Is there a simple equivalent in Swift
I have looked high and low for a solution and cant seem to find exactly what i am after.
Thanks
- HB
Because 2D arrays in swift can have subarrays with different lengths. There is no "matrix" type.
let arr = [
[1,2,3,4,5],
[1,2,3],
[2,3,4,5],
]
So the concept of "rows" and "columns" does not exist. There's only count.
If you want to count all the elements in the subarrays, (in the above case, 12), you can flat map it and then count:
arr.flatMap { $0 }.count
If you are sure that your array is a matrix, you can do this:
let rows = arr.count
let columns = arr[0].count // 0 is an arbitrary value
You must ask the size of a specific row of your array to get column sizes :
print("\(a.count) \(a[0].count)")
If you are trying to find the length of 2D array which in this case the number of rows (or # of subarrays Ex.[1,2,3]) you may use this trick: # of total elements that can be found using:
a.flatMap { $0 }.count //a is the array name
over # of elements in one row using:
a[0].count //so elemints has to be equal in each subarray
so your code to get the length of 2D array with equal number of element in each subarray and store it in constant arrayLength is:
let arrayLength = (((a.flatMap { $0 }.count ) / (a[0].count))) //a is the array name
I am trying to sum the elements of an array. WITHOUT using flatten. I have tried using the following:
def multi_array_sum(arr)
sum = 0
arr.each do |row|
row.each do |column|
sum += column
end
end
return sum
end
but unfortunately, it is not working. I am not sure how to iterate though a multidimensional array considering that I cannot use each if the first element in the array is not another array itself, for example, array = [[1, [1, 2], [3, 4, 5]].
If all elements are numeric or arrays, and you want to sum them all:
array.flatten.inject(:+)
Just use standard array functions and then enumerable.
array.flatten.reduce(:+)
If you are 100% sure that you cannot use flatten then you can use:
array.map { |a| a.reduce(:+) }.reduce(:+)
So if you absolutely can't use flatten (which is a bit weird), you can use a simple recursive method:
def multi_array_sum(arr)
case arr
when Fixnum
arr
when Array
arr.reduce(0) { |agg, sub_arr| agg + multi_array_sum(sub_arr) }
end
end
If each inner array is the same size and contains only numbers, you could use the method Matrix#[] to convert the array to a matrix, Matrix#each (without a block) to create an enumerator to generate the elements of the matrix, and Enumerable#reduce (aka inject) to compute the sum of all elements of the matrix.
require 'matrix'
def sum_all(arr)
Matrix[*arr].each.reduce(:+)
end
sum_all [[1,2],[3,4]] #=> 10
I need to take the numbers 0-8 and rearrange them randomly in a 3x3 array using a function. What is the simplest way possible?
I need to get [0,1,2,3,4,5,6,7,8] as a 3x3 array with the numbers in random order
One idea is to use a flat list/array with sorted numbers, shuffle them (e.g. using random.shuffle), then reshape it into. Python doesn't support arrays natively, so you can use lists instead, then reshape them into lists of list, like:
import random
def arrange(x, rows, cols):
random.shuffle(x)
return [x[cols * i : cols * (i + 1)] for i in range(rows)]
print(arrange(list(range(9)), 3, 3))
numpy has an array object that you can use also use, which supports reshaping etc, see the documentation, like:
import numpy as np
### Numpy's array solution
def arrange_np(x, rows, cols):
np.random.shuffle(x)
return x.reshape(rows, cols)
print(arrange_np(np.arange(9), 3, 3))
for the following code:
from array import *
x=[]
x.append(0.232)
print (x)
for i in range(25):
x[i+1]=(1/(i+1))-5*x[i]
I have this error:
x[i+1]=(1/(i+1))-5*x[i]
IndexError: list assignment index out of range
This may be happening because I have defined x to be an empty array. But how do I define the array and perform the same operation otherwise?
list is not designed for efficient mathematical operations and therefore its better to use numpy arrays for doing mathematical operations. However, if you want to use list, you may define a list initialized with n zero's using
x=[0]*n
x[0] = 0.232
x[1] = ....
....
Remember, that a multidimensional list created using above approach will refer to same element in the array! For example:
l = [0,0,0]*5
will be creating five same list's inside another list not separate list's. So its a bad idea to create multidimensional array like this!
A better way would be to create arrays using numpy using following code:
from numpy import empty, zeros
x = empty(n) # or # x = zeros(n)
x[0] = 0.232
x[1] = ....
....
and
l = empty((3,5)) # or # l = zeros((3,5))
for a array with 3 rows and 5 columns.