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 个)
Wayne King
2013-5-18
编辑:Wayne King
2013-5-18
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
类别
在 帮助中心 和 File Exchange 中查找有关 Programming 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!