スタンドアロンアプリ​ケーションで配列を引​数として渡す方法

6 vues (au cours des 30 derniers jours)
testudo
testudo le 26 Mar 2022
Commenté : testudo le 5 Avr 2022
function [res] = myfunc(arry,i)
res=sum(arry)/i;
disp(res);
上記のスクリプトをコンパイルして
> sh run_myfunc.sh /Applications/MATLAB_R2022a.app "1,2,3" 1
と実行したところ,答えが4.8571となり意図した動作をしません。
配列を引数に渡すにはどうすればよいのでしょうか。

Réponse acceptée

Kojiro Saito
Kojiro Saito le 4 Avr 2022
ターミナルから入力される場合、数値ではなく文字列として扱われてしまうためだと思われます。文字列(char)だったら数値(numまたはdouble)に変更するコードを追加すれば大丈夫です。
なお、iは虚数を表す予約変数名でもあるので、ここではnと表記しています。
function [res] = myfunc(arry, n)
if ischar(arry)
arry = str2num(arry);
end
if ischar(n)
n = str2double(n);
end
res=sum(arry)/n;
これをスタンドアロンアプリに変換して、以下のように実行します。
【実行例】
sh run_myfunc.sh /Applications/MATLAB_R2022a.app "1,2,3" 1
sh run_myfunc.sh /Applications/MATLAB_R2022a.app "[1,2,3]" 1
多次元の配列を渡す場合はセミコロンで行を区切ります。
sh run_myfunc.sh /Applications/MATLAB_R2022a.app "[1,2,3;1,2,3]" 1
  1 commentaire
testudo
testudo le 5 Avr 2022
配列の場合には str2num を使うのですね。実は str2double は試したのですがおかしな結果になってどうしたものかとおもっていたのでした。ありがとうございました。

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur データ型の変換 dans Help Center et File Exchange

Produits


Version

R2022a

Community Treasure Hunt

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

Start Hunting!