メインコンテンツ

このページの内容は最新ではありません。最新版の英語を参照するには、ここをクリックします。

if, elseif, else

条件が true の場合ステートメントを実行

構文

if expression
    statements
elseif expression
    statements
else
    statements
end

説明

if expression, statements, end は、を評価し、式が真 (true) であるときに一連のステートメントを実行します。結果が空でなく、非ゼロの要素 (論理値または実数値) のみが含まれる場合に、式は true になります。それ以外の場合は、false です。

elseif ブロックおよび else ブロックはオプションです。これらのステートメントは、直前の if...end ブロックの式が false の場合にのみ実行されます。if ブロックには、複数の elseif ブロックを含めることができます。

すべて折りたたむ

要素が 1 の行列を作成します。

nrows = 4;
ncols = 6;
A = ones(nrows,ncols);

行列全体をループして各要素に新しい値を代入します。主対角要素に 2 を、その隣接する対角に -1 を、それ以外のすべてに 0 を代入します。

for c = 1:ncols
    for r = 1:nrows
        
        if r == c
            A(r,c) = 2;
        elseif abs(r-c) == 1
            A(r,c) = -1;
        else
            A(r,c) = 0;
        end
        
    end
end
A
A = 4×6

     2    -1     0     0     0     0
    -1     2    -1     0     0     0
     0    -1     2    -1     0     0
     0     0    -1     2    -1     0

A > 0 のような配列の比較演算子を含む式は、結果のすべての要素が非ゼロの場合にのみ true になります。

関数 any を使用して結果が true のものがあるかどうかをテストします。

limit = 0.75;
A = rand(10,1)
A = 10×1

    0.8147
    0.9058
    0.1270
    0.9134
    0.6324
    0.0975
    0.2785
    0.5469
    0.9575
    0.9649

if any(A > limit)
    disp('There is at least one value above the limit.')
else
    disp('All values are below the limit.')
end
There is at least one value above the limit.

等価性をテストするには、== 演算子ではなく isequal を使用して配列を比較します。配列のサイズが異なる場合、== はエラーになるためです。

2 つの配列を作成します。

A = ones(2,3);
B = rand(3,4,5);

size(A)size(B) が同じ場合は配列を連結し、それ以外の場合は警告を表示して空の配列を返します。

if isequal(size(A),size(B))
   C = [A; B];
else
   disp('A and B are not the same size.')
   C = [];
end
A and B are not the same size.

strcmp を使用して文字ベクトルを比較します。等価性のテストに == を使用すると、文字ベクトルのサイズが異なる場合にエラーになります。

reply = input('Would you like to see an echo? (y/n): ','s');
if strcmp(reply,'y')
  disp(reply)
end

値が非ゼロかどうか判断します。非等価性をテストするには ~= 演算子を使用します。

x = 10;
if x ~= 0
    disp('Nonzero value')
end
Nonzero value

値が指定した範囲内にあるか判別します。

x = 10;
minVal = 2;
maxVal = 6;

if (x >= minVal) && (x <= maxVal)
    disp('Value within specified range.')
elseif (x > maxVal)
    disp('Value exceeds maximum value.')
else
    disp('Value is below minimum value.')
end
Value exceeds maximum value.

詳細

すべて折りたたむ

ヒント

  • 任意の数の if ステートメントを入れ子にすることができます。各 if ステートメントには、end キーワードが必要です。

  • elseif キーワード内のelse の後にスペースを追加しないでください (else if)。スペースにより、入れ子にされた if ステートメントが生じ、別の end キーワードが必要になります。

拡張機能

すべて展開する

C/C++ コード生成
MATLAB® Coder™ を使用して C および C++ コードを生成します。

バージョン履歴

R2006a より前に導入