
Logarithms on Matlab
Let's talk about logarithms in Matlab. Now, as you all know, logarithms are incredibly useful tools in mathematics, and they can help us solve a wide variety of problems. In this lesson, I'll show you how to calculate logarithms of any base in Matlab using some practical examples.
Natural logarithm
First, let's consider the natural logarithm. To calculate it, you simply use the "log(x)" function.
log(x)
For instance, to find the natural logarithm of 9, you would type log(9) and Matlab would return the value of 2.1972.
>> log(9)
ans = 2.1972
The natural logarithm of 9 is 2.1972.
$$ \ln 9 = \log_e 9= 2.1972 $$
If you type log(exp(1)), the function returns 1 because e1=e
>> log(exp(1))
ans = 1
Base 10 logarithm
To calculate the base 10 logarithm, use the function log10(x)
log10(x)
For example, to calculate the base 10 logarithm of 9, type the command log10(9)
>> log10(9)
ans = 0.95424
The base 10 logarithm of 9 is 0.95424.
$$ \log_{10} 9 = 0.95424 $$
If you type log10(10), the function returns 1 because 101=10.
>> log10(10)
ans = 1
Base 2 logarithm
Matlab also has a specific function to calculate the base 2 logarithm. It is the function log2(x)
log2(x)
For example, to calculate the base 2 logarithm of 9, type the function log2(x)
>> log2(9)
ans = 3.1699
The base 2 logarithm of 9 is 3.1699.
$$ \log_2 9 = 3.1699 $$
If you type log2(2), the function returns 1 because 21=2.
>> log2(2)
ans = 1
Logarithms in other bases
But what about logarithms of other bases? Fear not! If you need to find the logarithm of a number with a base other than e, 10, or 2, you can use the change-of-base formula.
$$ \log_A x = \frac{\log_B x}{\log_B A} $$
This formula states that the logarithm of x to base A is equal to the logarithm of x to base B divided by the logarithm of A to base B. Easy peasy!
For example, if you want to find the logarithm of 16 to base 4, you can use the change-of-base formula with the logarithms in base 10.
$$ \log_4 16 = \frac{\log_{10} 16}{\log_{10} 4} $$
In this case, the starting base is B=10 while the target base is A=4.
Write the conversion formula on Matlab by typing this expression: log10(16)/log10(4)
>> log10(16)/log10(4)
ans = 2
The logarithm of 16 in base 4 is equal to 2.
$$ \log_4 16 = \frac{\log_{10} 16}{\log_{10} 4} = 2 $$
If you do a quick verification, the result (2) is correct.
$$ 4^2 = 16 $$
And if you're more comfortable with natural logarithms, you can use those as well. The answer will still be 2.
>> log(16)/log(4)
ans = 2
>> log2(16)/log2(4)
ans = 2
So, there you have it! Now you know how to calculate logarithms of any base in Matlab.