首页 > 解决方案 > 在 Matlab 中创建 if else 语句以选择正确的矩阵

问题描述

我是 matlab 新手(和一般编程),我正在尝试创建一个 if else 语句,它允许我选择正确的旋转矩阵,但是当我的代码运行时,当我输入选择时会导致错误。我添加了我的屏幕截图我的代码1和我获得的命令窗口错误2。先感谢您。

代码

%% Creating a matrix Rot reprensenting the rotatinal transformation that is applied. 

theta = input('Input the value of angle: ');

% Chose the direction 

Dir = input('Input around which axis the rotation occurs (x,y or z): '); % this creates an error 

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.')
end

在此处输入图像描述

在此处输入图像描述

标签: matlabif-statementmatrix

解决方案


将输入解析为字符串

我认为唯一需要改变的是如何input()解析它。旋转轴,Dir可以解析为字符串,'s'允许在以下 if 条件下使用。's'可以通过input()→的第二个输入参数来指示input('Please enter something','s')

或者,正如Thomas建议的那样,对引号指示的输入使用字符串表示法也可以'x''y'或者'z'(不确定它们是否在 MATLAB 版本之间存在任何差异)。

代码片段:

Dir = input('Input around which axis the rotation occurs (x,y,z): ','s');

方法 1:使用 If-Else 语句

%% Creating a matrix Rot reprensenting the rotatinal transformation that is applied. 
theta = input('Input the value of angle: ');

% Chose the direction 
Dir = input('Input around which axis the rotation occurs (x,y or z): ', 's'); % this creates an error 

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.')

end

方法 2:使用开关盒

theta = input('Input the value of angle: ');
Dir = input('Input around which axis the rotation occurs (x,y,z): ','s');


switch Dir
    case "x"
        disp('x-case');
        Rot = [1 0 0;0 cosd(theta) -sind(theta);0 sind(theta) cos(theta)];

    case "y"
        disp('y-case');
        Rot = [cosd(theta) 0 sind(theta);0 1 0;0 -sind(theta) cos(theta)];

    case "z"
        disp('z-case');
        Rot = [cosd(theta) -sind(theta) 0;0 sind(theta) cos(theta);0 0 1];

    otherwise
        disp('Not a valid axis');           
end

%Continue code below the corresponding Rot will be selected%

推荐阅读