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

19 visualizzazioni (ultimi 30 giorni)
testudo
testudo il 26 Mar 2022
Commentato: testudo il 5 Apr 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となり意図した動作をしません。
配列を引数に渡すにはどうすればよいのでしょうか。

Risposta accettata

Kojiro Saito
Kojiro Saito il 4 Apr 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 Commento
testudo
testudo il 5 Apr 2022
配列の場合には str2num を使うのですね。実は str2double は試したのですがおかしな結果になってどうしたものかとおもっていたのでした。ありがとうございました。

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su データ型の変換 in Help Center e File Exchange

Prodotti


Release

R2022a

Community Treasure Hunt

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

Start Hunting!