The triangular inequality states that for any two vectors u and v, the magnitude of the sum of u and v is less than or equal to the sum of the magnitudes of u and v.
We can verify the triangular inequality in MATLAB using the following code:
main.m428 chars12 lines
We first define the vectors u and v. Then we calculate the left-hand side (lhs) of the triangular inequality by taking the absolute value of the sum of u and v. We calculate the right-hand side (rhs) of the triangular inequality by taking the sum of the absolute values of u and v.
We then check if the triangular inequality holds by verifying that each element of lhs is less than or equal to the corresponding element of rhs. If the inequality holds for all elements of lhs, then we conclude that the triangular inequality holds for the vectors u and v. If not, we conclude that the triangular inequality does not hold for the vectors u and v.
Note that we use the sum
function with the logical expression lhs <= rhs
to count the number of elements for which the inequality holds. If this count is equal to the length of lhs, then the triangular inequality holds.
gistlibby LogSnag