verify triangular inequality in matlab

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.m
u = [1 2 3]; % define vector u
v = [4 5 6]; % define vector v

lhs = abs(u + v); % calculate the absolute value of the sum of u and v
rhs = abs(u) + abs(v); % calculate the sum of the absolute values of u and v

if sum(lhs <= rhs) == length(lhs) % verify the triangular inequality
    disp('The triangular inequality holds for vectors u and v.')
else
    disp('The triangular inequality does not hold for vectors u and v.')
end
428 chars
12 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