将 if/else 语句转换为允许多个选择的代码

Converting an if/else statement into a code that allows for more than one choice

因此,我正在尝试以能够使用多个选项的方式转换以下代码。 (案例内部发生的事情并不重要,我只是想弄清楚如何同时使用多个案例)

%% 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

我尝试使用 switches/cases 或条件,但无法获得不同的结果。

这段代码的结尾objective是为了能够选择应力张量的旋转方向。我的代码适用于简单的情况,但我希望它能够在不重新运行代码的情况下计算 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 旋转与围绕 [=14] 旋转产生不同的结果=] 先 X,即使每个轴的旋转角度相同。