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

9 views (last 30 days)
testudo
testudo on 26 Mar 2022
Commented: testudo on 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となり意図した動作をしません。
配列を引数に渡すにはどうすればよいのでしょうか。

Accepted Answer

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

Sign in to comment.

More Answers (0)

Categories

Find more on データ型の変換 in Help Center and File Exchange

Products


Release

R2022a

Community Treasure Hunt

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

Start Hunting!