How can I create function that have char input arguments?

Hello everybody,
I made a function that caculates rotation in each axes.
==================================================================================
function R=rot(dir,ang)
switch dir
case 'x'
R=[1 0 0 0;0 cos(ang) -sin(ang) 0;0 sin(ang) cos(ang) 0;0 0 0 1];
case 'y'
R=[cos(ang) 0 sin(ang) 0; 0 1 0 0;-sin(ang) 0 cos(ang) 0;0 0 0 1];
case 'z'
R=[cos(ang) -sin(ang) 0 0;sin(ang) cos(ang) 0 0;0 0 1 0;0 0 0 1];
otherwise
error=1;
end
==================================================================================
When I try to run this function, a error message shows like,
=================================================================
??? SWITCH expression must be a scalar or string constant.
Error in ==> rot at 3 switch dir =================================================================
I think I should make this function to recognize char input. How can I solve thie error?

Answers (1)

How are you inputting dir to the function, are you inputting it as
'x', 'y', or 'z'?
It should work. I'm using direc below because dir is a MATLAB function name.
direc = 'z';
ang = pi/2;
switch direc
case 'x'
R=[1 0 0 0;0 cos(ang) -sin(ang) 0;0 sin(ang) cos(ang) 0;0 0 0 1];
case 'y'
R=[cos(ang) 0 sin(ang) 0; 0 1 0 0;-sin(ang) 0 cos(ang) 0;0 0 0 1];
case 'z'
R=[cos(ang) -sin(ang) 0 0;sin(ang) cos(ang) 0 0;0 0 1 0;0 0 0 1];
otherwise
error('Direction not recognized');
end
You should call the function like this:
R = rot('x',pi/2);
for example

1 Comment

Oops, I didn't known that 'dir' is a MATLAB function name.
You're answer helped a lot! Thanks!!!

Sign in to comment.

Categories

Find more on Programming in Help Center and File Exchange

Tags

Asked:

on 18 May 2013

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!