So I am trying to convert the following code in way that I would be able to use more than just one of the choices. (What happens inside of the cases does not matter, I would simply like to figure out how I could use more than one cases at once)
%% 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
I tried using switches/cases or conditions, but I wasn't able to obtain a different results.
The end objective of this code is to be able to choose which direction a stress tensor will be rotated. My code works for simple cases, but i would like it to be able to calculate with a 30degree rotation in x and a 45 in y for example without rerunning the code.
To answer your question about code flow, the simplest replacement to a chain of if/elseif/else
is to use a switch
statement.
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
Alternatively, you could also use a flag system like mentionned in @Tasos Papastylianou comment under your question. It is a bit more technical to implement but a perfectly good solution too.
Now this only take care about the code flow. The actual validity of the calculations in each case is up to you. For the rotation about more than one axis, remember that the order in which you apply the rotations is important: rotating around X
first, then around Y
, can yield a different result than rotating around Y
first then X
, even if the rotation angles for each axis were the same.