定义一个返回nxn方阵的函数

时间:2017-03-17 04:51:15

标签: python-2.7 numpy scipy

我只是在学习pyhton并希望定义一个返回nxn方阵的函数,其中主对角线(i = j),上对角线(j = i + 1)和下对角线(j = i)的预定义值-1)和所有其他元素相等0.

任何帮助将不胜感激,

感谢

<html>
    <head>
        <title>Ajax file upload</title>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
        <script>
            $(document).ready(function (e) {
            $("#uploadimage").on('submit', (function(e) {
            e.preventDefault();
                    $.ajax({
                    url: "upload.php", // Url to which the request is send
                            type: "POST", // Type of request to be send, called as method
                            data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
                            contentType: false, // The content type used when sending data to the server.
                            cache: false, // To unable request pages to be cached
                            processData:false, // To send DOMDocument or non processed data file it is set to false
                            success: function(data)   // A function to be called if request succeeds
                            {
                            alert(data);
                            }
                    });
            }));
        </script>
    </head>
    <body>
        <div class="main">
            <h1>Ajax Image Upload</h1><br/>
            <hr>
            <form id="uploadimage" action="" method="post" enctype="multipart/form-data">
                <div id="image_preview"><img id="previewing" src="noimage.png" /></div>
                <hr id="line">
                <div id="selectImage">
                    <label>Select Your Image</label><br/>
                    <input type="file" name="file" id="file" required />
                    <input type="submit" value="Upload" class="submit" />
                </div>
            </form>
        </div>
    </body>
</html>

2 个答案:

答案 0 :(得分:2)

如果a,b,c分别是上对角线,主对角线和下对角线的三个列表,您可以按如下方式编写:

import numpy as np
a=[1,2,3,4]
b=[5,6,7,8,9]
c=[10,11,12,13]
n=len(b)
m=np.zeros((n,n))
for i in range(0,n-1):
    m[i,i+1]=a[i]
    m[i,i]=b[i]
    m[i+1,i]=c[i]
m[n-1,n-1]=b[n-1]
print(m)

在上面的代码中,您初始化零矩阵,然后根据您的列表仅更新上,下和主对角线条目。 输出是

[[  5.   1.   0.   0.   0.]
 [ 10.   6.   2.   0.   0.]
 [  0.  11.   7.   3.   0.]
 [  0.   0.  12.   8.   4.]
 [  0.   0.   0.  13.   9.]]

编辑:@hpaulj建议的缩短方式是

m=np.diag(a,1)+np.diag(b,0)+np.diag(c,-1)

np.diag(r,k)创建一个矩阵,其中主对角线上方的k'对角线(如果k下方为负值)为r,其余条目为0

请参阅此处的文档: https://docs.scipy.org/doc/numpy/reference/generated/numpy.diag.html

答案 1 :(得分:0)

这是一个方法,它使用numpy.diag接受在对角线上添加的项目列表,并利用k参数指定我们想要修改的对角线。

import numpy as np

def create_diag(n, l):
    arr = np.zeros((n, n))

    # check that l contains an odd number of elements
    if len(l) % 2 != 1:
        return arr

    # check that we have at most the number of diagonals in the matrix
    if len(l) >= 2*n:
        return arr

    # set limits of diagonals to set. setting 3 diagonals means limits=[-1,0,1]. setting 1 diagonal means limits=[0]
    limit = int((len(l) - 1) / 2)
    limits = range(-limit, limit + 1)

    # maps k-->list of values on the diagonal
    diag_map = dict(zip(limits, l))
    for k, v in diag_map.items():
        diag = [v] * (n - abs(k))
        arr += np.diag(diag, k=k)
    return arr

# elements to put on the diagonal, centered about the main diagonal (i=j)
l = [-1,1,2]
n = 6

diag_arr = create_diag(n, l)

# [[ 1.  2.  0.  0.  0.  0.]
#  [-1.  1.  2.  0.  0.  0.]
#  [ 0. -1.  1.  2.  0.  0.]
#  [ 0.  0. -1.  1.  2.  0.]
#  [ 0.  0.  0. -1.  1.  2.]
#  [ 0.  0.  0.  0. -1.  1.]]