13.2 判定分岐 タスク1 doPlot が 1 の場合にのみの条件の設定について

8 Ansichten (letzte 30 Tage)
佳奈子 浜口
佳奈子 浜口 am 14 Jun. 2021
Beantwortet: Atsushi Ueno am 14 Jun. 2021
if ブロックの本体は、条件が true の場合にのみ実行されます。
doPlot1 の場合にのみプロット用コードの 4 ~ 7 行目が実行されるように、スクリプトを変更します。
こちらの問題の解答がif doPlot=1 ではなく if doPlot になるのは何故でしょうか?
解答
if doPlot
%% <プロット コード>;
end

Akzeptierte Antwort

Atsushi Ueno
Atsushi Ueno am 14 Jun. 2021
>こちらの問題の解答がif doPlot=1 ではなく if doPlot になるのは何故でしょうか?
【回答】"if doPlot==1"でも"if doPlot"でも文法的に正しく、同じ意味になるからです。
    但し"if doPlot=1"は文法エラーです。"=="は「比較」の意味、"="は「代入」の意味だからです。
【詳細】doPlotは下記の通り0または1をランダムに設定します。
doPlot = randi([0 1])
"doPlot==1"を式として評価すると、doPlotが1の時:真(true)、doPlotが0の時:偽(false)となります。
"doPlot"を式として評価すると、doPlotが非ゼロの時:真(true)、doPlotがゼロの時:偽(false)になります。
つまりdoPlotが0か1の値を取る場合は、"if doPlot==1"でも"if doPlot"でも文法的に正しく、結果は同じです。
>if expression, statements, end は、を評価し、式が真 (true) であるときに一連のステートメントを実行します。結果が空でなく、非ゼロの要素 (論理値または実数値) のみが含まれる場合に、式は true になります。それ以外の場合は、false です。

Weitere Antworten (0)

Kategorien

Mehr zu ループと条件付きステートメント finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!