Assad Ebrahim
Assad Ebrahim

Reputation: 6361

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. 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

However, this means that rot(45) must return a matrix in a form that can then be multiplied immediately by the vector.

To do this I've defined the following function, using the [ R ] syntax to indicate multiple return values:

 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.

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

Any idea what's going wrong?

Thanks,

Upvotes: 0

Views: 2436

Answers (1)

Floris
Floris

Reputation: 46365

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.

Upvotes: 2

Related Questions