if and else in matlab code example

Example 1: matlab if

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

Example 2: if statement in matlab

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

Example 3: matlab if statement

if r == c
  A(r,c) = 2;
elseif abs(r-c) ~= 1
  A(r,c) = -1;
else
  A(r,c) = 0;
end

Example 4: matlab else if

if expression
    statements
elseif expression
    statements
else
    statements
end

Tags:

Misc Example