Task 03

数组操作

数组操作
numpy.ndarray.shape表示数组的维度,返回一个元组,这个元组的长度就是维度的数组,即ndim属性(秩)。

import numpy as np

x = np.array([1,2,9,4,5,6,7,8])
print(x.shape)  #(8,)
x.shape = [2,4]  #定义数组维度,可自定义几行几列
print(x)
# [[1 2 9 4]
#  [5 6 7 8]]
`numpy.ndarray.flat`将数组转换为一维的迭代器,可以用for访问数组每一个元素。
import numpy as np

x = np.array([[11, 12, 13, 14, 15],
              [16, 17, 18, 19, 20],
              [21, 22, 23, 24, 25],
              [26, 27, 28, 29, 30],
              [31, 32, 33, 34, 35]])
y = x.flat
print(y)
# <numpy.flatiter object at 0x0000020F9BA10C60>
for i in y:
    print(i, end=' ')
# 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35

y[3] = 0  #

print(end='\n')
print(x)
# [[11 12 13  0 15]
#  [16 17 18 19 20]
#  [21 22 23 24 25]
#  [26 27 28 29 30]
#  [31 32 33 34 35]]
`numpy.ndarray.flatten([order='C'])`将数组的副本转换为一维数组,并返回。
order:'C' -- 按行,'F' -- 按列,'A' -- 原顺序,'k' -- 元素在内存中的出现顺序。
import numpy as np   #  flatten函数

x = np.array([[11, 12, 13, 14, 15],
              [16, 17, 18, 19, 20],
              [21, 22, 23, 24, 25],
              [26, 27, 28, 29, 30],
              [31, 32, 33, 34, 35]])
y = x.flatten()
print(y)
# [11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 
#  35]

y[3] = 0  #此处数字不影响结果,但也不能没有数字
print(x)
# [[11 12 13 14 15]
#  [16 17 18 19 20]
#  [21 22 23 24 25]
#  [26 27 28 29 30]
#  [31 32 33 34 35]]

x = np.array([[11, 12, 13, 14, 15],
              [16, 17, 18, 19, 20],
              [21, 22, 23, 24, 25],
              [26, 27, 28, 29, 30],
              [31, 32, 33, 34, 35]])

y = x.flatten(order='F')  #规定按列打印数组元素
print(y)
# [11 16 21 26 31 12 17 22 27 32 13 18 23 28 33 14 19 24 29 34 15 20 25 30  
#  35]

y[3] = 0
print(x)
# [[11 12 13 14 15]
#  [16 17 18 19 20]
#  [21 22 23 24 25]
#  [26 27 28 29 30]
#  [31 32 33 34 35]]

数组转置
numpy.transpose(a, axes=None)Permute the dimensions of an array.
numpy.ndarray.TSame as self.transpose(),except that self is returned if self.ndim<2.

import numpy as np
x = np.random.rand(5, 5) * 10
x = np.around(x, 2)
print(x)
# [[0.21 3.52 9.31 8.6  4.94]
#  [1.67 0.14 1.76 5.91 1.36]
#  [3.48 9.05 5.76 3.41 5.94]
#  [9.25 6.12 7.42 7.8  4.18]
#  [2.79 5.77 4.63 1.06 2.07]]
y = x.T
print(y)
# [[0.21 1.67 3.48 9.25 2.79]
#  [3.52 0.14 9.05 6.12 5.77]
#  [9.31 1.76 5.76 7.42 4.63]
#  [8.6  5.91 3.41 7.8  1.06]
#  [4.94 1.36 5.94 4.18 2.07]]
y = np.transpose(x)
print(y)
# [[0.21 1.67 3.48 9.25 2.79]
#  [3.52 0.14 9.05 6.12 5.77]
#  [9.31 1.76 5.76 7.42 4.63]
#  [8.6  5.91 3.41 7.8  1.06]
#  [4.94 1.36 5.94 4.18 2.07]]

更改维度
numpy.newaxis = None None

import numpy as np

x = np.array([1, 2, 9, 4, 5, 6, 7, 8])
print(x.shape)  # (8,)
print(x)  # [1 2 9 4 5 6 7 8]

y = x[np.newaxis, :]
print(y.shape)  # (1, 8)
print(y)  # [[1 2 9 4 5 6 7 8]]

y = x[:, np.newaxis]
print(y.shape)  # (8, 1)
print(y)
# [[1]
#  [2]
#  [9]
#  [4]
#  [5]
#  [6]
#  [7]
#  [8]]
`numpy.squeeze(a, axis=None)`从数组的形状中删除单维度条目,即吧shape中的1的维度去掉。
`a`表示输入的数组;
`axis`用于指定需要删除的维度,但是指定的维度必须为单维度,否则将会报错。
import numpy as np

x = np.array([[[0], [1], [2]]])
print(x.shape)  
print(x)
# [[[0]
#   [1]
#   [2]]]
y = np.squeeze(x)
print(y.shape)  #(3,)
print(y)  # [0 1 2]

y = np.squeeze(x, axis=0)
print(y.shape)
print(y)
# [[0]
#  [1]
#  [2]
y = np.squeeze(x, axis=2)
print(y.shape)#  (1, 3)
print(y)  # [[0 1 2]]

y = np.squeeze(x, axis=1)
# ValueError: cannot select an axis to squeeze out which has size not equal to one
import numpy as np
import matplotlib.pyplot as plt

x = np.array([[1, 4, 9, 16, 25]])
x = np.squeeze(x)
print(x.shape)  # (5, )
plt.plot(x)
plt.show()

在这里插入图片描述
数组结合
数组之间可以进行拼接操作
numpy.concatenate((a1, a2, ...), axis=1, out=None)Join a sequence of arrays along an existing axis.

import numpy as np
#  拼接前和拼接后的维数不变。如原来x, y都是一维时,拼接后也是一维。

x = np.array([1, 2, 3])
y = np.array([7, 8, 9])
z = np.concatenate([x, y])
print(z)
# [1 2 3 7 8 9]

z = np.concatenate([x, y], axis=0)
print(z)
# [1 2 3 7 8 9]
`numpy.stack(arrays, axis=1, out=None)`Join a sequence of arrays along a new axis.
import numpy as np

x = np.array([1, 2, 3])
y = np.array([7, 8, 9])
z = np.stack([x, y])  #  stack是增加维度的拼接
print(z.shape)  # (2, 3)
print(z)
# [[1 2 3]
#  [7 8 9]]

z = np.stack([x, y], axis=1)
print(z.shape)  # (3, 2)
print(z)
# [[1 7]
#  [2 8]
#  [3 9]]
`hstack(),vstack()`分别表示水平和竖直的拼接方式。在数据维度等于1时,比较特殊。而当维度大于或等于2时,它们的作用相当于`concatenate`,用于在已有轴上进行操作。
import numpy as np

a = np.hstack([np.array([1, 2, 3, 4]), 5])
print(a)  # [1 2 3 4 5]

a = np.concatenate([np.array([1, 2, 3, 4]), 5])
print(a)
# ValueError: all the input arrays must have same number of dimensions, but the array at index 0 has 1 dimension(s) and the array at index 1 has 0 dimension(s)

数组拆分
numpy.split(ary, indices_or_sections, axis=0) Split an array into multiple sub-arrays as views into ary.

import numpy as np  #  垂直切分是按数组高度切分  
  
x = np.array([[11, 12, 13, 14],
              [16, 17, 18, 19],
              [21, 22, 23, 24]])
y = np.vsplit(x, 3)
print(y)
# [array([[11, 12, 13, 14]]), array([[16, 17, 18, 19]]), array([[21, 22, 23, 24]])]

y = np.split(x, 3)
print(y)
# [array([[11, 12, 13, 14]]), array([[16, 17, 18, 19]]), array([[21, 22, 23, 24]])]


y = np.vsplit(x, [1])
print(y)
# [array([[11, 12, 13, 14]]), array([[16, 17, 18, 19],
#        [21, 22, 23, 24]])]

y = np.split(x, [1])
print(y)
# [array([[11, 12, 13, 14]]), array([[16, 17, 18, 19],
#        [21, 22, 23, 24]])]


y = np.vsplit(x, [1, 3])
print(y)
# [array([[11, 12, 13, 14]]), array([[16, 17, 18, 19],
#        [21, 22, 23, 24]]), array([], shape=(0, 4), dtype=int32)]
y = np.split(x, [1, 3], axis=0)
print(y)
# [array([[11, 12, 13, 14]]), array([[16, 17, 18, 19],
#        [21, 22, 23, 24]]), array([], shape=(0, 4), dtype=int32)]
import numpy as np  #  水平切分是按宽度切分
  
x = np.array([[11, 12, 13, 14],
              [16, 17, 18, 19],
              [21, 22, 23, 24]])
y = np.hsplit(x, 2)
print(y)
# [array([[11, 12],
#        [16, 17],
#        [21, 22]]), array([[13, 14],
#        [18, 19],
#        [23, 24]])]

y = np.split(x, 2, axis=1)
print(y)
# [array([[11, 12],
#        [16, 17],
#        [21, 22]]), array([[13, 14],
#        [18, 19],
#        [23, 24]])]

y = np.hsplit(x, [3])
print(y)
# [array([[11, 12, 13],
#        [16, 17, 18],
#        [21, 22, 23]]), array([[14],
#        [19],
#        [24]])]

y = np.split(x, [3], axis=1)
print(y)
# [array([[11, 12, 13],
#        [16, 17, 18],
#        [21, 22, 23]]), array([[14],
#        [19],
#        [24]])]

y = np.hsplit(x, [1, 3])
print(y)
# [array([[11],
#        [16],
#        [21]]), array([[12, 13],
#        [17, 18],
#        [22, 23]]), array([[14],
#        [19],
#        [24]])]

y = np.split(x, [1, 3], axis=1)
print(y)
# [array([[11],
#        [16],
#        [21]]), array([[12, 13],
#        [17, 18],
#        [22, 23]]), array([[14],
#        [19],
#        [24]])]

数组平铺
numpy.tile(A, reps) Construct an array by repeating A the number of times given by reps.

import numpy as np  #  将原矩阵横向、纵向复制

x = np.array([[1, 2], [3, 4]])
print(x)
# [[1 2]
#  [3 4]]

y = np.tile(x, (1, 3))
print(y)
# [[1 2 1 2 1 2]
#  [3 4 3 4 3 4]]

y = np.tile(x, (3, 1))
print(y)
# [[1 2]
#  [3 4]
#  [1 2]
#  [3 4]
#  [1 2]
#  [3 4]]

y = np.tile(x, (3, 3))
print(y)
# [[1 2 1 2 1 2]
#  [3 4 3 4 3 4]
#  [1 2 1 2 1 2]
#  [3 4 3 4 3 4]
#  [1 2 1 2 1 2]
#  [3 4 3 4 3 4]]

numpy.repeat(a, repeats, axis=None) Repeat elements of an array.
axis=0,沿着y轴复制,实际上增加了行数。
axis=1,沿着x轴复制,实际上增加了列数。
repeats,可以为一个数,也可以为一个矩阵。
axis=None时就会flatten当前矩阵,实际上就是变成了一个行向量。

import numpy as np  #  重复数组的元素

x = np.repeat(3, 4)
print(x)  # [3 3 3 3]

x = np.array([[1, 2], [3, 4]])
y = np.repeat(x, 2)
print(y)
# [1 1 2 2 3 3 4 4]

y = np.repeat(x, 2, axis=0)
print(y)
# [[1 2]
#  [1 2]
#  [3 4]
#  [3 4]]

y = np.repeat(x, 2, axis=1)
print(y)
# [[1 1 2 2]
#  [3 3 4 4]]

y = np.repeat(x, [2, 3], axis=0)
print(y)
# [[1 2]
#  [1 2]
#  [3 4]
#  [3 4]
#  [3 4]]

y = np.repeat(x, [2, 3], axis=1)
print(y)
# [[1 1 2 2 2]
#  [3 3 4 4 4]]
/* USER CODE BEGIN Header */ /** ****************************************************************************** * File Name : freertos.c * Description : Code for freertos applications ****************************************************************************** * @attention * * <h2><center>© Copyright (c) 2025 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** */ /* USER CODE END Header */ /* Includes ------------------------------------------------------------------*/ #include "FreeRTOS.h" #include "task.h" #include "main.h" #include "cmsis_os.h" /* Private includes ----------------------------------------------------------*/ /* USER CODE BEGIN Includes */ #include"stdio.h" #include"usart.h" /* USER CODE END Includes */ /* Private typedef -----------------------------------------------------------*/ /* USER CODE BEGIN PTD */ typedef struct { uint32_t var1; uint32_t var2; uint32_t var3; }DataGroup; /* USER CODE END PTD */ /* Private define ------------------------------------------------------------*/ /* USER CODE BEGIN PD */ /* USER CODE END PD */ /* Private macro -------------------------------------------------------------*/ /* USER CODE BEGIN PM */ /* USER CODE END PM */ /* Private variables ---------------------------------------------------------*/ /* USER CODE BEGIN Variables */ /* USER CODE END Variables */ osThreadId Task_KEYHandle; osThreadId myTask01Handle; osThreadId myTask02Handle; osThreadId myTask03Handle; osMessageQId myQueue01Handle; /* Private function prototypes -----------------------------------------------*/ /* USER CODE BEGIN FunctionPrototypes */ /* USER CODE END FunctionPrototypes */ void StartTask_KEY(void const * argument); void StartTask01(void const * argument); void StartTask02(void const * argument); void StartTask03(void const * argument); void MX_FREERTOS_Init(void); /* (MISRA C 2004 rule 8.1) */ /* GetIdleTaskMemory prototype (linked to static allocation support) */ void vApplicationGetIdleTaskMemory( StaticTask_t **ppxIdleTaskTCBBuffer, StackType_t **ppxIdleTaskStackBuffer, uint32_t *pulIdleTaskStackSize ); /* USER CODE BEGIN GET_IDLE_TASK_MEMORY */ static StaticTask_t xIdleTaskTCBBuffer; static StackType_t xIdleStack[configMINIMAL_STACK_SIZE]; void vApplicationGetIdleTaskMemory( StaticTask_t **ppxIdleTaskTCBBuffer, StackType_t **ppxIdleTaskStackBuffer, uint32_t *pulIdleTaskStackSize ) { *ppxIdleTaskTCBBuffer = &xIdleTaskTCBBuffer; *ppxIdleTaskStackBuffer = &xIdleStack[0]; *pulIdleTaskStackSize = configMINIMAL_STACK_SIZE; /* place for user code */ } /* USER CODE END GET_IDLE_TASK_MEMORY */ /** * @brief FreeRTOS initialization * @param None * @retval None */ void MX_FREERTOS_Init(void) { /* USER CODE BEGIN Init */ /* USER CODE END Init */ /* USER CODE BEGIN RTOS_MUTEX */ /* add mutexes, ... */ /* USER CODE END RTOS_MUTEX */ /* USER CODE BEGIN RTOS_SEMAPHORES */ /* add semaphores, ... */ /* USER CODE END RTOS_SEMAPHORES */ /* USER CODE BEGIN RTOS_TIMERS */ /* start timers, add new ones, ... */ /* USER CODE END RTOS_TIMERS */ /* Create the queue(s) */ /* definition and creation of myQueue01 */ osMessageQDef(myQueue01, 16, uint32_t); myQueue01Handle = osMessageCreate(osMessageQ(myQueue01), NULL); /* USER CODE BEGIN RTOS_QUEUES */ /* add queues, ... */ /* USER CODE END RTOS_QUEUES */ /* Create the thread(s) */ /* definition and creation of Task_KEY */ osThreadDef(Task_KEY, StartTask_KEY, osPriorityNormal, 0, 128); Task_KEYHandle = osThreadCreate(osThread(Task_KEY), NULL); /* definition and creation of myTask01 */ osThreadDef(myTask01, StartTask01, osPriorityIdle, 0, 128); myTask01Handle = osThreadCreate(osThread(myTask01), NULL); /* definition and creation of myTask02 */ osThreadDef(myTask02, StartTask02, osPriorityIdle, 0, 128); myTask02Handle = osThreadCreate(osThread(myTask02), NULL); /* definition and creation of myTask03 */ osThreadDef(myTask03, StartTask03, osPriorityIdle, 0, 128); myTask03Handle = osThreadCreate(osThread(myTask03), NULL); /* USER CODE BEGIN RTOS_THREADS */ /* add threads, ... */ /* USER CODE END RTOS_THREADS */ } /* USER CODE BEGIN Header_StartTask_KEY */ /** * @brief Function implementing the Task_KEY thread. * @param argument: Not used * @retval None */ /* USER CODE END Header_StartTask_KEY */ void StartTask_KEY(void const * argument) { /* USER CODE BEGIN StartTask_KEY */ /* Infinite loop */ uint32_t ProducerValue=0; DataGroup myDataGroup_t={10,20,30}; ProducerValue=(uint32_t)&myDataGroup_t; for(;;) { if(HAL_GPIO_ReadPin(GPIOA,GPIO_PIN_13)==0) { osDelay(10); if(HAL_GPIO_ReadPin(GPIOA,GPIO_PIN_13)==0) { if(osMessagePut(myQueue01Handle,ProducerValue,100)!=osOK) { osThreadSuspendAll(); printf("send fail!\r\n"); osThreadResumeAll(); } else { printf("send success!\r\n"); osThreadResumeAll(); } while(HAL_GPIO_ReadPin(GPIOA,GPIO_PIN_13)==0) { osDelay(10); } } } osDelay(1); } /* USER CODE END StartTask_KEY */ } /* USER CODE BEGIN Header_StartTask01 */ /** * @brief Function implementing the myTask01 thread. * @param argument: Not used * @retval None */ /* USER CODE END Header_StartTask01 */ void StartTask01(void const * argument) { /* USER CODE BEGIN StartTask01 */ /* Infinite loop */ osEvent event; DataGroup *myDataGroup_r; for(;;) { event=osMessageGet(myQueue01Handle,osWaitForever); if(event.status==osEventMessage) { myDataGroup_r=event.value.p; osThreadSuspendAll(); printf("va1 is %d\r\n",myDataGroup_r->var1); printf("va2 is %d\r\n",myDataGroup_r->var2); printf("va3 is %d\r\n",myDataGroup_r->var3); osThreadResumeAll(); } osDelay(1); } /* USER CODE END StartTask01 */ } /* USER CODE BEGIN Header_StartTask02 */ /** * @brief Function implementing the myTask02 thread. * @param argument: Not used * @retval None */ /* USER CODE END Header_StartTask02 */ void StartTask02(void const * argument) { /* USER CODE BEGIN StartTask02 */ /* Infinite loop */ osEvent event; DataGroup *myDataGroup_r; for(;;) { event=osMessageGet(myQueue01Handle,osWaitForever); if(event.status==osEventMessage) { myDataGroup_r=event.value.p; osThreadSuspendAll(); printf("var1 is %d\r\n",myDataGroup_r->var1); printf("var2 is %d\r\n",myDataGroup_r->var2); printf("var3 is %d\r\n",myDataGroup_r->var3); osThreadResumeAll(); } osDelay(1); } /* USER CODE END StartTask02 */ } /* USER CODE BEGIN Header_StartTask03 */ /** * @brief Function implementing the myTask03 thread. * @param argument: Not used * @retval None */ /* USER CODE END Header_StartTask03 */ void StartTask03(void const * argument) { /* USER CODE BEGIN StartTask03 */ /* Infinite loop */ for(;;) { osDelay(1); } /* USER CODE END StartTask03 */ } /* Private application code --------------------------------------------------*/ /* USER CODE BEGIN Application */ /* USER CODE END Application */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ myTask03可以怎么写
最新发布
06-07
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值