# .if

Perform element-wise conditional operations with array-type predicates

Since R2023b

Parent Section: equationsintermediates

## Syntax

.if Predicate1
Branch1
.elseif Predicate2
Branch2
.else
Branch3
.end

## Description

You can perform element-wise conditional operations with array-type predicates by using .if statements. These statements are similar to if statements, but in an if statement, predicates must be scalar. To evaluate array-type predicates, use .if statements.

The following rules and restrictions apply:

• Every .if requires an .else.

• .elseif branches are optional. Any subsequent .elseif branch must have a predicate of the same size and shape as the original .if branch predicate.

• Each branch of the .if-.elseif-.else statement must match the size and shape of the predicates. Scalar expansion applies.

Whether scalar expansion is necessary is determined on a branch-by-branch basis, so using an array in one branch and a scalar in another is allowed.

• Units must be commensurate between branches.

• Terminate an .if statement with the .end keyword.

• Output is an array of the same size and shape as the .if branch predicate. For multiple return values, each output variable is the same size and shape as the predicate.

Array-type predicates are not supported for:

• Conditional sections

• Mode charts

• Assert statements

## Examples

expand all

Perform conditional assignment to an intermediate based on array-type predicates:

component my_comp
inputs
pred1 = [1 0 0];
pred2 = [0 0 1];
end
parameters
A = [1 2 3];
B = [4 5 6];
C = [7 8 9];
end
intermediates
y = .if pred1, A; .elseif pred2, B; .else C; .end
end
... % Other parameters, variables, equations
end

With these input values, the intermediate y evaluates to [1 8 6] because:

• The first element of pred1 is true, so the first value is the first element of parameter A

• The second element of neither pred1 or pred2 is true, so the second value is the second element of parameter C

• The third element of pred2 is true, so the third value is the third element of parameter B

This component represents a vectorized saturation block:

component vec_saturation
inputs
I = zeros([3 3]);
end

outputs
ITrue = zeros(size(I));
end

parameters
upper_limit = 5;
lower_limit = 0.7;
end

equations
ITrue == .if I>=upper_limit, upper_limit;
.elseif I <= lower_limit, lower_limit;
.else I;
.end
end
end
• If I is within the bounds specified by the upper_limit and lower_limit parameters, ITrue is equal to I.

• If the value of I is outside the bounds, ITrue saturates to the upper limit or lower limit, respectively.

## Version History

Introduced in R2023b