How to insert variables (string) in MATLAB function

1 回表示 (過去 30 日間)
Pk Verma
Pk Verma 2021 年 10 月 25 日
コメント済み: Pk Verma 2021 年 10 月 25 日
function R=rotmatx(axis,q)
if axis=='x'
R=[1 0 0;0 cos(q) -sin(q); 0 sin(q) cos(q)];
elseif axis=='y'
R=[cos(q) 0 sin(q); 0 1 0; -sin(q) 0 cos(q)];
elseif axis=='z'
R=[cos(q) -sin(q) 0;-sin(q) cos(q) 0; 0 0 1];
else
fprintf('invalid axis');
end
so, i want the output when i call this function
rotmatx('x','t')
the output should be
[1, 0, 0]
[0, cos(t), -sin(t)]
[0, sin(t), cos(t)]
but there is error.
Can someone please help me out for this.
Thank You.

採用された回答

Walter Roberson
Walter Roberson 2021 年 10 月 25 日
rotmatx('y', 'p')
ans = 
rotmatx('z', pi/6)
ans = 
function R=rotmatx(axis,q)
Q = sym(q);
if axis=='x'
R=[1 0 0;0 cos(Q) -sin(Q); 0 sin(Q) cos(Q)];
elseif axis=='y'
R=[cos(Q) 0 sin(Q); 0 1 0; -sin(Q) 0 cos(Q)];
elseif axis=='z'
R=[cos(Q) -sin(Q) 0;-sin(Q) cos(Q) 0; 0 0 1];
else
fprintf('invalid axis');
end
end

その他の回答 (1 件)

KSSV
KSSV 2021 年 10 月 25 日
編集済み: KSSV 2021 年 10 月 25 日
syms t
R=[1 0 0;0 cos(t) -sin(t); 0 sin(t) cos(t)]
R = 
  3 件のコメント
KSSV
KSSV 2021 年 10 月 25 日
You can follow the above method and write into a function.
Pk Verma
Pk Verma 2021 年 10 月 25 日
Do you mean this
function R=tst(t)
syms t
R=[1 0 0;0 cos(t) -sin(t); 0 sin(t) cos(t)];
end
now
tst('p')
now output is...
[1, 0, 0]
[0, cos(t), -sin(t)]
[0, sin(t), cos(t)]
but output should be
[1, 0, 0]
[0, cos(p), -sin(p)]
[0, sin(p), cos(p)]
if i done anything wrong then please write function and then function calling code.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeCalculus についてさらに検索

製品


リリース

R2021a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by