Assume you are working on a new edition of MATLAB for The MathWorks. So far, in
ID: 3696667 • Letter: A
Question
Assume you are working on a new edition of MATLAB for The MathWorks. So far, in this new addition, MATLAB knows how to do the following:
• arithmetic operations (+, -, *,/)
• logical operations (<,<=,==,>=, >, &&, ||, ~,~=)
• conditional statements (if… elseif… else… end) • loops (while loop, for loop)
• I/O (display, input())
• Scalars, vectors, and matrices
It is now your job to create additional functionality in MATLAB by implementing the following functions:
• my_sqrt(x) calculates the square root of x
• my_abs(x) calculates the absolute value of x
• my_max(X) finds the maximum value of X and its position, i.e. index
• my_sort(X) sorts the values of X in increasing order
You can assume that x is a scalar and X is a vector. You can further assume that that x and X contain numerical values. You are NOT allowed to use any of MATLAB’s existing functions but need to design your own which should only use MATLAB’s capabilities described above.
Explanation / Answer
>> 1+2*3
>> (1+2)*3
An example with addition and division
In the first case the division has higher precedence so 4 / 2 is evaluated first to give 2, then 1 is added to give 3.
The result is the same as the first case. Why?
The brackets force the addition to be evaluated first to give 3, then 4 is divided by 3 to give 1.3333
>> 4/2+1
>> 1+4/2
>> 4/(2+1)
An example with powers and division
In the first case 8 is squared first to give 64, which is then divided by 3 to give 21.3333
In the second case, 8 is raised to the power 2/3 giving 4.
>> 8^2/3
>> 8^(2/3)
Remember that operations of the same precedence are evaluated left to right. For example, try
In the first case, 12 is divided by 2 first to give 6, then 6 is divided by 3 to give 2.
In the second case the brackets force 2 * 3 = 6 to be evaluated first, then 12 / 6 = 2. This version is usually clearer.
>> 12/2/3
>> 12/(2*3)
For another example, try
In the first case 43 = 64 is evaluated first, which is then squared to give 4096.
In the second case 32=9 is evaluated first and then 49=262144.
This is the same as the first case, but clearer.
>> 4^3^2
>> 4^(3^2)
>> (4^3)^2
One potentially confusing operation is when minus - is used with just one argument to indicate a change in sign. For example, try
The -3 is treated as a number, so you get -6, but this is unclear.
>> 2*-3
So use brackets to make it clear what you mean. Instead type
>> 2*(-3)
One more example with minus used to indicate a negative number.
Again -3 is treated as a number, so 2-3 = 1/8 = 0.125
>> 2^-3
Use brackets to make it clear what you mean. Instead type
>> 2^(-3)
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.