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?

Antworten (1)

Wayne King
Wayne King am 18 Mai 2013
Bearbeitet: Wayne King am 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 Kommentar

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

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Programming finden Sie in Hilfe-Center und File Exchange

Tags

Gefragt:

am 18 Mai 2013

Community Treasure Hunt

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

Start Hunting!

Translated by