簡體   English   中英

在 Matlab 中創建 if else 語句以選擇正確的矩陣

[英]Creating if else statement in Matlab for choosing the correct matrix

我是 matlab(和一般編程)的新手,我正在嘗試創建一個 if else 語句,允許我選擇正確的旋轉矩陣,但是當我的代碼運行時,當我輸入選擇時會導致錯誤。 我添加了我的截圖我的代碼1和命令 window 錯誤我得到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%

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM