Skip to main content

Section 1.2 Assigning scalar values

The command

x = 3/4

assigns the value of 0.75 to variable x. Matlab will also display the result of this assignment (the number 0.75) to you. Most of the time, we do not need it to print the result of every computation. Ending a command with a semicolon ; suppresses the output: try

x = 3/4;

Now that the variable x has a value, we can use it in computations. For example,

y = x^2 + 5*x - 1

will result in y being assigned the value 3.3125. It is important to realize that every variable must be assigned a value before it can be used on the right hand side of an assignment. If we try to execute y = x^2 without assigning any value to x, the result will be an error: x is undefined.

It is important to understand the difference between equations and assignments. In mathematics, \(x = x + 1\) is an equation which has no solutions. In Matlab,

x = x + 1;

is an assignment command which means “take the current value of x, add 1 to it, and assign the result to x”. The effect is that the value of x is increase by 1.

Write a script that does the following. Assign two unequal positive numbers to x and y (for example, two different digits of your SUID). Compute their arithmetic mean \(a = \dfrac{x+y}{2}\) and geometric mean \(g = \sqrt{xy}\text{.}\) Then display the arithmetic mean of \(a\) and \(g\text{.}\) Finally, display the geometric mean of \(a\) and \(g\text{.}\)

Answer
x = 4; 
y = 7;
a = (x+y)/2;
g = sqrt(x*y);
disp((a+g)/2)
disp(sqrt(a*g))

Remark: Karl Gauss discovered that if the above process of taking arithmetic and geometric means is repeated, both these means quickly converge to the same number. This number is called the arithmetic-geometric mean of x and y. It is linked to certain integrals which cannot be evaluated with calculus methods, and therefore provides an efficient computational approach to such integrals. For more, see Wikipedia.