简体   繁体   English

定义作用于python中矩阵的函数

[英]defining a function acting on a matrix in python

I want to define a reasonably simple function to swap two entries in a matrix, currently I have the following code: 我想定义一个相当简单的函数来交换矩阵中的两个条目,目前我有以下代码:

def swap (n[a][b] ,direction):

    if direction==1:             #to the left
        entry=n[a][b]
        n[a][b]=n[a-1][b]
        n[a-1][b]=entry

I'm struggling to find a way to make it so that when I enter a variable eg current (where current =matrix[3][2] ) the contents of the if clause act with a=3 ,b=2 on the target matrix. 我正在努力寻找一种方法来使它,以便当我输入变量(例如current (其中current =matrix[3][2] ))时, if子句的内容在目标上以a=3 ,b=2起作用矩阵。

I'm not quite sure if this is what you want, but at least it is working python code: 我不太确定这是否是您想要的,但至少它在运行python代码:

import numpy as np

def swap(M, a, b, direction):
     if direction == 1:
         entry = M[a,b]
         M[a,b] = M[a-1,b]
         M[a-1,b] = entry

#create a test matrix
np.random.seed(10)
n = np.random.rand(10, 100, size=(3,2))

print n
n = swap(n,2,1,1)
print n

This outputs: 输出:

[[19 25]
 [74 38]
 [99 39]]

[[19 25]
 [74 39]
 [99 38]]

So the 38 and 39 were swapped. 因此38和39被交换了。

Expanding on @interjay comment, here is a working function (assuming that matrix is list of lists): 扩展@interjay注释,这是一个工作函数(假设矩阵是列表列表):

def swap(m, r, c, direction):
    if direction == 1:
        m[r][c], m[r-1][c] = m[r-1][c], m[r][c]

parameters: 参数:

  • m is matrix you want to act on, m是您要作用的矩阵,
  • r is a row of the element you want to swap, r是要交换的元素的一行,
  • c is a column of the element you want to swap, c是您要交换的元素的列,
  • direction is direction of swap. direction是交换的方向。

Usage example: 用法示例:

A = [[1, 2], [3, 4]]
print A
swap(A, 1, 1, 1)
print A

output: 输出:

[[1, 2], [3, 4]]
[[1, 4], [3, 2]]

Also note, that usually, but not necessary, first index corresponds to row or line and second corresponds to column. 还要注意,通常(但不是必需),第一个索引对应于行或行,第二个索引对应于列。 In this case so swapping n[a][b] with n[a-1][b] in your code is equivalent to moving element n[a][b] upwards one row, not to the left. 在这种情况下,将n[a][b]与代码中的n[a-1][b]交换等效于将元素n [a] [b]向上移动一行,而不是向左移动。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM