如何将生成触觉刺激数组的重复代码改写为循环?
Hey there! I totally get that writing repetitive code to create 10 separate zero arrays feels clunky—let's streamline this with a clean loop. Here are two easy approaches to generate your stim1 through stim10 arrays without redundancy:
Option 1: Store arrays in a list (simple and efficient)
Using a list keeps things straightforward, and you can access each stimulus array via its index (e.g., stim_list[0] for the first one, equivalent to stim1).
import numpy as np # First, keep your existing rand_stim_seconds function (or use the optimized version below!) def rand_stim_seconds(array): lst = list(range(0,10)) random_ints = [] for i in lst: rand_int = np.random.uniform(0.1, 0.6, 1) random_ints.append(rand_int) values = [] for j in random_ints: d = j * 22050 e = float(d) f = int(np.round(e)) values.append(f) add_lst = [0] for k in values: add = add_lst[-1] + k if add > 44100: break add_lst.append(add) for l in add_lst[1:]: array[l] = 1 return array # Generate 10 independent stimulus arrays stim_list = [] for _ in range(10): # Create a brand new zero array each time to avoid overwriting data new_stim_array = np.zeros(44100, dtype=int) stim_list.append(rand_stim_seconds(new_stim_array)) # Access example: stim_list[0] is your first stimulus array, stim_list[9] the tenth
Option 2: Store arrays in a dictionary (for named access)
If you prefer keeping the stim1 to stim10 naming convention, a dictionary lets you access each array by its name directly.
# Generate 10 named stimulus arrays stim_dict = {} for num in range(1, 11): new_stim_array = np.zeros(44100, dtype=int) stim_dict[f"stim{num}"] = rand_stim_seconds(new_stim_array) # Access example: stim_dict["stim1"], stim_dict["stim2"], etc.
Bonus: Optimize your rand_stim_seconds function
Since you're working with numpy, we can simplify your function using vectorized operations (faster and cleaner than loops):
def rand_stim_seconds(array): # Generate 10 random intervals in one line (no loop needed) random_intervals = np.random.uniform(0.1, 0.6, 10) # Convert intervals to array indices in a single vectorized step values = np.round(random_intervals * 22050).astype(int) add_lst = [0] for k in values: next_pos = add_lst[-1] + k if next_pos > 44100: break add_lst.append(next_pos) # Assign 1s to all target positions at once (no loop) array[add_lst[1:]] = 1 return array
The key thing here is that we create a new zero array inside each loop iteration—this ensures each stimulus array is independent and doesn't get overwritten by previous calls to the function.
内容的提问来源于stack exchange,提问作者sallicap

