如何将变量赋给numpy矩阵

时间:2016-10-16 06:36:04

标签: python numpy matrix

我想创建一个生成旋转矩阵R的函数。这是我的代码:

import numpy as np
def R(theta):
    a = np.cos(theta)
    b = -1*np.sin(theta)
    c = np.sin(theta)
    d = np.cos(theta)
    return np.matrix('a b; c d')

但它有这样的错误

raise TypeError("Invalid data string supplied: " + astr)
TypeError: Invalid data string supplied: a

有什么建议吗?

2 个答案:

答案 0 :(得分:0)

使用.format将变量放入字符串形式

Executing tasks: [:leafsnap:clean, :leafsnap:generateDebugSources, :leafsnap:generateDebugAndroidTestSources, :leafsnap:mockableAndroidJar, :leafsnap:prepareDebugUnitTestDependencies, :leafsnap:assembleDebug]

Configuration on demand is an incubating feature.
Observed package id 'add-ons;addon-google_apis-google-24' in inconsistent location 'C:\Users\Butters Stotch\AppData\Local\Android\Sdk\add-ons\addon-google_apis-google-24-1' (Expected 'C:\Users\Butters Stotch\AppData\Local\Android\Sdk\add-ons\addon-google_apis-google-24')
Already observed package id 'add-ons;addon-google_apis-google-24' in 'C:\Users\Butters Stotch\AppData\Local\Android\Sdk\add-ons\addon-google_apis-google-24'. Skipping duplicate at 'C:\Users\Butters Stotch\AppData\Local\Android\Sdk\add-ons\addon-google_apis-google-24-1'
Incremental java compilation is an incubating feature.
:leafsnap:clean
:leafsnap:preBuild UP-TO-DATE
:leafsnap:preDebugBuild UP-TO-DATE
:leafsnap:checkDebugManifest
:leafsnap:preReleaseBuild UP-TO-DATE
:leafsnap:prepareComAndroidSupportAppcompatV72100Library
:leafsnap:prepareComAndroidSupportSupportV42100Library
:leafsnap:prepareComGoogleAndroidGmsPlayServices6171Library
:leafsnap:prepareSeEmilsjolanderStickylistheaders252Library
:leafsnap:prepareDebugDependencies
:leafsnap:compileDebugAidl
:leafsnap:compileDebugRenderscript
:leafsnap:generateDebugBuildConfig
:leafsnap:mergeDebugShaders
:leafsnap:compileDebugShaders
:leafsnap:generateDebugAssets
:leafsnap:mergeDebugAssets
:leafsnap:generateDebugResValues UP-TO-DATE
:leafsnap:generateDebugResources
:leafsnap:mergeDebugResources
:leafsnap:processDebugManifest
:leafsnap:processDebugResources FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':leafsnap:processDebugResources'.
> com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command 'C:\Users\Butters Stotch\AppData\Local\Android\Sdk\build-tools\21.0.0\aapt.exe'' finished with non-zero exit value -1073741819

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

答案 1 :(得分:0)

那个矩阵表示法:

a = np.matrix('1 2; 3 4')

仅适用于文字,而不适用于变量;使用标量变量,您可以使用括号表示法

np.matrix([[1, 2], [3, 4]])
np.matrix([[a, b], [c, d]])

这一部分,[[a, b], [c, d]]是一个普通的Python列表(列表)。 np.matrix(...)然后获取此列表并将其转换为numpy矩阵。

但实际上,你应该使用

np.array(...)
编写

np.matrix是为了让MATLAB访问者熟悉这些内容。大多数numpy工作是array,而不是matrix

另一点 - a = np.cos(theta)theta一起使用的是标量或数组。但是,如果一个数组,而不是a本身将是一个数组,而不是一个标量。构建此旋转矩阵时应注意这一点。