I'm trying to write a code that will add 2 arrays(element by element) and store them in a 3rd array.
Basic Logic:
arr3[i] = arr1[i] arr2[i]
For this, I have created two arrays arr1 and arr2. The result of the sum of arr1 and arr2 is getting appended in an empty array arr3.
code:
from numpy import append, array, int8
arr1 = array([1,2,3,4,5])
arr2 = array([2,4,6,8,10])
len = max(arr1.size,arr2.size)
arr3 = array([],dtype=int8)
for i in range(len):
append(arr3,arr1[i] arr2[i])
print(arr1[i] arr2[i])
print(arr3[i])
print(arr3)
In this code, I'm able to refer to elements of arr1 and arr2 and add them, but I'm not able to append the data to arr3.
Can anyone please help me to understand, what is the mistake in the code due to which I'm not able to store the data to arr3?
CodePudding user response:
You can simply use
arr3 = arr1 arr2
The reason why your code doesn't work is that append doesn't mutate the array, but returns a new one. You can simply modify your code like this:
for i in range(len):
arr3 = append(arr3,arr1[i] arr2[i])
CodePudding user response:
First things first
Do Not Use built-in function name as variable.
len is a built-in function in python.
@sagi's answer is right. Writing the for loop would mean your code is not time-optimized.
But if you still want to understand where your code went wrong, check array shape
import numpy as np
arr3 = np.array([],dtype=int8)
print (arr3.shape)
>>> (0,)
Maybe you can create an empty array of the same shape as arr1 or arr2. Seems like for your problem they have same dimension.
arr3 = np.empty(arr1.shape, dtype=arr1.dtype)
arr3[:] = arr1 arr2
If you are still persisting to use the dreaded for loop and numpy.append then use this--
arr3 = np.empty(arr1.shape, dtype=arr1.dtype)
for i in range(len(arr1)):
np.append(arr3, arr1[i] arr2[i])
print(arr3)
>>> array([ 3, 6, 9, 12, 15])
Cheers, good luck!!
