问题描述
因此,我尝试以能够使用多种选择的方式转换以下代码。 (案例内部发生了什么并不重要,我只是想弄清楚如何一次使用多个案例)
%% Creating a matrix Rot representing the rotational transformation that is applied.
theta = input('Input the value of angle: ');
% Choose the direction
Dir = input('Input around which axis the rotation occurs (x,y or z): ','s');
if Dir == 'x'
Rot = [1 0 0;0 cosd(theta) -sind(theta);0 sind(theta) cos(theta)];
elseif Dir == 'y'
Rot = [cosd(theta) 0 sind(theta);0 1 0;0 -sind(theta) cos(theta)];
elseif Dir == 'z'
Rot = [cosd(theta) -sind(theta) 0;0 sind(theta) cos(theta);0 0 1];
else
disp('Not an axis.')
Rot = input('Input Rotational Transformation Matrix: ')
end
我尝试使用开关/案例或条件,但我无法获得不同的结果。
此代码的最终目标是能够选择应力张量的旋转方向。我的代码适用于简单的情况,但我希望它能够在不重新运行代码的情况下计算 x 中的 30 度旋转和 y 中的 45 度旋转。
解决方法
要回答有关代码流的问题,最简单的 if/elseif/else
链替代方法是使用 switch
语句。
switch Dir
% for a single axis rotation
case 'x'
% Code for a rotation about a single axes ('X')
case 'y'
% Code for a rotation about a single axes ('Y')
case 'z'
% Code for a rotation about a single axes ('Z')
%% For complex rotation about more than one axes
case 'xy'
% Code for a rotation about 2 axes ('X' and 'Y')
case 'xz'
% Code for a rotation about 2 axes ('X' and 'Z')
case 'yz'
% Code for a rotation about 2 axes ('Y' and 'Z')
case 'xyz'
% Code for a rotation about 3 axes ('X','Y' and 'Z')
otherwise
% advise user to re-input "Dir"
end
或者,您也可以使用 flag 系统,如在您的问题下的@Tasos Papastylianou 评论中提到的那样。实现起来有点技术性,但也是一个完美的解决方案。
现在只关心代码流。每种情况下计算的实际有效性取决于您。对于围绕多个轴的旋转,请记住应用旋转的顺序很重要:首先围绕 X
旋转,然后围绕 Y
旋转,与围绕 {{1} 旋转可以产生不同的结果}} 先然后Y
,即使每个轴的旋转角度相同。