简体   繁体   English

如何在Matlab / Octave中定义矩阵值函数—返回值语法

[英]How to define a matrix valued function in Matlab/Octave — return value syntax

I'm trying to verify some matrix rotation calculations, and thought it would be easiest to drop into Octave (Matlab) and define a simple function to do this. 我正在尝试验证一些矩阵旋转计算,并认为最简单的方法是放入Octave(Matlab)并定义一个简单的函数来执行此操作。 But I am stymied by some syntax difficulties that I think are due to returning a matrix (multiple values). 但是,我认为某些语法困难使我感到困惑,这归因于返回矩阵(多个值)。

Ideally, I'd like to be able to key in something simple, where I can choose the rotation degree and the point to be rotated, for example: 理想情况下,我希望能够键入一些简单的内容,在其中可以选择旋转角度和要旋转的点,例如:

rot(45)*[1 0]'  % rotate unit vector by 45 degrees

I'd expect to get back the correct answer: 0.70711 0.70711 我希望得到正确的答案: 0.70711 0.70711

However, this means that rot(45) must return a matrix in a form that can then be multiplied immediately by the vector. 但是,这意味着rot(45)必须以可以立即与向量相乘的形式返回矩阵。

To do this I've defined the following function, using the [ R ] syntax to indicate multiple return values: 为此,我定义了以下函数,使用[R]语法指示多个返回值:

 function [ R ] = rot(th_deg)
    [ cos(th_deg * pi/180)  -sin(th_deg * pi/180) ;
      sin(th_deg) * pi/180)  cos(th_deg * pi/180)   ]
 end

Calling function rot(45) by itself works fine and shows the correct 2x2 rotation matrix. 单独调用函数rot(45)可以正常工作,并显示正确的2x2旋转矩阵。

But trying to use this rotation matrix returned value in the further multiplication yields the warning message: warning: some elements in list of return values are undefined 但是尝试在进一步的乘法中使用此旋转矩阵返回值会产生警告消息: warning: some elements in list of return values are undefined

Any idea what's going wrong? 知道发生了什么事吗?

Thanks, 谢谢,

That is because as written, calling your function will print the result but not return it. 这是因为按照编写的方式,调用函数将打印结果,但不会返回结果。

Try 尝试

function [ R ] = rot(th_deg)
  R = [ cos(th_deg * pi/180)  -sin(th_deg * pi/180) ;
  sin(th_deg) * pi/180)  cos(th_deg * pi/180)   ];
end

Note the ; 注意; to suppress output of the result when the function is called, and setting R= in order to return a result. 抑制在调用函数时输出结果,并设置R=以便返回结果。

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

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