matlab - 在 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
解决方案
将输入解析为字符串
我认为唯一需要改变的是如何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%
推荐阅读
- javascript - ThreeJS 加载 GLTF 并使用 FabricJS 画布作为纹理
- vue.js - "Mustache" syntax alternative for Vue template when using Pug language
- python - Scrapy startproject 不起作用权限被拒绝:蜘蛛
- amazon-web-services - 为什么我无法从我的 PC 连接到新的 AWS Aurora Serverless 实例?
- excel - 如何按颜色对表格列进行排序?
- html - 如何在表格边界内对齐文本输入元素?
- python - 枚举 Pandas 数据框后,字典条目都相同
- python - Django & Celery - 跨多个方法和文件发送信号
- typescript - Firebase 数据库出现意外令牌错误
- c# - Microsoft.EntityFrameworkCore ProjectTo() 找不到我的存储库的方法定义