6.4: Logical Functions
- Page ID
- 84714
\( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \) \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)\(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\) \(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\)\(\newcommand{\AA}{\unicode[.8,0]{x212B}}\)
The first step is to create a logical function, which is a function that returns a logical value. The following function takes three input variables, a
, b
, and c
, and returns true (1
) if they form a Pythagorean triple and false (0
) otherwise.
function res = is_pythagorean(a, b, c)
if a^2 + b^2 == c^2
res = 1;
else
res = 0;
end
end
We can use this function like so:
>> is_pythagorean(3, 4, 5)
ans = 1
But we can write the same function more concisely, like this:
function res = is_pythagorean(a, b, c)
res = a^2 + b^2 == c^2;
end
The result of the equality operator is a logical value, which we can assign directly to res
.
Put this function in a file called is_pythagorean.m, so we can use it as part of our program.