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?

回答(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 个评论

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

请先登录,再进行评论。

类别

帮助中心File Exchange 中查找有关 Programming 的更多信息

标签

提问:

2013-5-18

Community Treasure Hunt

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

Start Hunting!

Translated by