PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, May 13, 2022

[FIXED] How to append an array within a for loop that gets new outputs every loop?

 May 13, 2022     append, arrays, for-loop, python     No comments   

Issue

I am trying to create a for loop that appends an array generated from a function that can only convert to an array. The following is the code:

array2 = np.array([])
for i in range(len(fps)):
    array1 = np.array([])
    DataStructs.ConvertToNumpyArray((fps[i]), array1)
    np.append(array1,array2)
    
array2

fps is a list of 634 elements, where each element has a length of 1024. The DataStructs.ConvertToNumpyArray function can only compute one entry at a time and stores the output in an array (array1 in the code above). The following is an output for one entry (there are nonzero elements but within):

array([0., 0., 0., ..., 0., 0., 0.])

How can I use a for loop to store all 634 elements in one array?


Solution

array2 = np.array([])
for i in range(len(fps)):
    array1 = np.array([])
    DataStructs.ConvertToNumpyArray((fps[i]), array1)

    # you need to assign the concatenated array to array2
    array2 = np.append(array2,array1)
    
array2



# if you want to have a 2D-array as output, you can do the following:

# initialize the array then assign new elements to it
array2 = np.zeros(shape=(len(fps),1024))
for i in range(len(fps)):
    array1 = np.array([])
    DataStructs.ConvertToNumpyArray((fps[i]), array1)
    array2[i] = array1
    
array2

# or you can use np.concatenate
array2 = np.zeros(shape=(0,1024))
for i in range(len(fps)):
    array1 = np.array([])
    DataStructs.ConvertToNumpyArray((fps[i]), array1)
    array2 = np.concatenate((array2,[array1]))



Answered By - fusion
Answer Checked By - David Goodson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing