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?

Réponses (1)

Wayne King
Wayne King le 18 Mai 2013
Modifié(e) : Wayne King le 18 Mai 2013
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 commentaire

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

Connectez-vous pour commenter.

Catégories

En savoir plus sur Programming dans Centre d'aide et File Exchange

Tags

Question posée :

le 18 Mai 2013

Community Treasure Hunt

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

Start Hunting!

Translated by