You are on page 1of 12

1.

5 Variables and assignments

Variable and assignment basics

A program uses a variable to remember values as the program executes instructions.

Here's a variation on a common schoolchild riddle. Use the numPeople box to remember the
number of people as you proceeded through each step.

PARTICIPATION
ACTIVITY 1.5.1: People on bus.

For each step, keep track of the current number of people by typing in the numPeople
box (it's editable).

Start

You are driving a bus. Memory


The bus starts with 5 people.
??
5 numPeople
??
??

1 2 3 4 5

Check Next

Feedback?

By the way, the real riddle's ending question is actually "What is the bus driver's name?"— the
subject usually says "How should I know?". The riddler then says "I said, YOU are driving a bus."

A variable is a named place for a programmer to store data in memory. A programmer de nes a
new variable by writing a statement like age = 20; where age has not been previously de ned.
The interpreter negotiates with the computing system to allocate a memory location for the new
variable. In MATLAB®, the details of such negotiation are hidden from the programmer. However,
to illustrate what is happening behind the scenes, the below animation shows a small portion of
the computer system's memory, in particular memory locations with addresses 96-99.

bl
PARTICIPATION 1.5.2: Variables in memory.
ACTIVITY

Start 2x speed

Memory

age = 20;
96 ??
nextAge = age; 97 20 age
98 ??
99 20 nextAge

Captions 
1. Interpreter obtains memory for age. Interpreter writes 20 into age.
2. Interpreter obtains memory for nextAge. Interpreter writes current value of age into
nextAge.

Feedback?

The MATLAB statement age = 20; causes the interpreter to rst nd space in memory to
store the variable named age. The interpreter happens to obtain memory location 97 for age, to
which the interpreter then writes the value 20. The second statement nextAge = age;
causes allocation of another memory location, in this case location 99, after which the
interpreter reads the current value of variable age (which is 20), and writes that value into
nextAge.

An assignment statement such as age = 20; or nextAge = age; upon being executed,
writes (i.e., assigns) the current value of the item on the ='s right side into the variable on the ='s
left side. The "=" is known as the assignment operator. An assignment statement has one of the
following two forms, where the optional semicolon suppresses printing of the result of the
assignment statement to the command window:

Expressions will be described later; for now, the expression may be a number like "20" or a
variable.

Construct 1.5.1: Assignment statement.

variable = expression;
variable = expression

Feedback?
PARTICIPATION
ACTIVITY 1.5.3: De ning numeric variables.

1) Write a variable assignment


statement that assigns Answers

totalPets with 3. totalPets = 3; or totalPets = 3

The value 3 was assigned to totalPets.

Check Show answer

2) Write a variable assignment


statement that assigns Answer

luckyNumber with 7 and luckyNumber = 7;


suppresses the output to the
The value 7 was assigned to luckyNumber. The
command window.
semicolon suppresses printing to the command
window.

Check Show answer

3) Write a variable assignment


statement that assigns Answer

birdFeeders with the current birdFeeders = stockCount


value of variable stockCount,
Reads the current value of stockCount and
and prints the value of the
writes that value into birdFeeders. The lack of a
variable to the command
semicolon causes the value to be printed to the
window. command window.

Check Show answer

Feedback?

Reading and writing variables

The following example uses three variables named numFriends, peopleIKnow, and
peopleTheyKnow. The animation shows how the variables are written and read by each
statement, while being maintained in the base workspace. The base workspace stores variables
created at the command line. The example illustrates how interactions between people grow in
a social network. Note how variables are initialized, their values are read, and how values are
written back into the variables.

PARTICIPATION
1.5.4: People-known example: Statements write and read variables'
ACTIVITY memory locations.

Start 2x speed

>> friends = 200 Name Value


>> peopleIKnow = friends
friends 200
peopleIKnow = 200
peopleIKnow 200
>> peopleTheyKnow = peopleIKnow * friends
peopleTheyKnow 8000000
peopleTheyKnow = 40000
>> peopleTheyKnow = peopleTheyKnow * friends
peopleTheyKnow = 8000000 Workspace
>>
Command window

Captions 
1. Interpreter allocates memory for variables when variables are rst assigned.
2. "peopleIKnow" is assigned the value of "friends", so "peopleIKnow" is assigned the
value 200.
3. "peopleTheyKnow" is assigned the value of "peopleIKnow" times "friends". So
"peopleTheyKnow" is assigned the value 40000.
4. Assignment reads current values of "peopleTheyKnow" and "friends", multiplies, and
writes the result back into "peopleTheyKnow".

Feedback?

The statement peopleTheyKnow = peopleTheyKnow * numFriends confuses some


new programmers, who ask "How can peopleTheyKnow be equal to
peopleTheyKnow * numFriends? Don't those values have to be different?" However, "="
does NOT mean "equals", but rather means "compute the value of the expression on the right
and write the result into the variable on the left." So the meaning of the statement is: "Compute
the value of peopleTheyKnow * numFriends, and write the result into peopleTheyKnow."
So if peopleTheyKnow is currently 40,000 and numFriends is 200, then the value of
peopleTheyKnow after executing that statement will be 8,000,000.

A common misconception among new programmers is that an assignment statement


somehow permanently connects the items on the left and right sides of the "=" operator. Such
permanent connection matches the use of "=" in mathematics, indicating that the left and right
sides are equivalent. However, "=" in MATLAB implies no such connection or equivalency. Rather,
when the interpreter executes the assignment statement, the interpreter simply reads the
current value of the statement's right side and writes that value into the variable on the left side.
An arrow pointing to the left might have been a better symbol than "=" to convey the meaning of
assignment, and thus some other languages use "<=" or ":=" to represent assignment.

PARTICIPATION
ACTIVITY 1.5.5: Variable assignments.

1) What is the value stored in


luckyNumber after these two Answer
statements execute? 4

The second write to luckyNumber overwrites the


luckyNumber = 7;
luckyNumber = 4; rst value written into the variable.

Check Show answer

2) Assume apples currently has


the value 5 and oranges the Answer
value 9. What is the value 6
stored in apples after the
5 + 1 yields 6
following statement?

apples = apples + 1;

Check Show answer

3) Assume apples currently has


the value 5 and oranges the Answer
value 9. What is the value 9
stored in apples after the
apples gets the value of oranges, or 9. Oranges
following statements?
then gets 9+1 or 10, but that doesn't affect apples.

apples = oranges;
oranges = oranges + 1;

Check Show answer

4) Write a statement, ending with


"- 1;", that decreases the value Answer
stored in apples by 1. The apples = apples - 1;
output of the statement should Reads the value of apples, subtracts 1, and writes
be suppressed. the result back into apples.

Check Show answer

5) Write two statements, the rst


setting apples to 7, and the Answer
second setting oranges to
apples plus one. Terminate apples = 7;
each statement with a oranges = apples + 1;
semicolon. "apples = 7" must be done rst, then "oranges =
apples + 1" will store 7+1 or 8 into oranges.

Check Show answer

Feedback?

Swapping variables

A common error is to overwrite the value in a variable before that variable's value was used. The
animation below shows code that initially fails in swapping two variable values, because the rst
assignment overwrites the initial value, which is then lost and thus not used in the second
assignment. One way to avoid such an error is to assign a temporary variable, such as shown in
the animation. The code in the gure further below shows the failed swap and the successful
swap.

PARTICIPATION
ACTIVITY 1.5.6: Swapping using a temporary variable.

Start 2x speed

>> firstBid = 85; Name Value

>> secondBid = 119; firstBid 119


>> firstBid = secondBid; secondBid 119
>> secondBid = firstBid;
Command window Workspace
>> firstBid = 85; Name Value
>> secondBid = 119;
firstBid 119
>> tempBid = firstBid;
secondBid 85
>> firstBid = secondBid;
tempBid 85
>> secondBid = tempBid;
Command window Workspace

Captions 
1. rstBid is assigned 85 and secondBid is assigned 119.
2. rstBid is assigned secondBid which makes rstBid equal to 119.
3. secondBid is assigned rstBid which equals 119. This swap fails.
4. Just like above, rstBid is assigned 85 and secondBid is assigned 119.
5. A variable called tempBid is created and tempBid is assigned rstBid.
6. rstBid is assigned secondBid which is assigned 119.
7. secondBid is assigned tempBid, which is equal to rstBid, which is equal to 85. This
swap succeeds.

Feedback?

PARTICIPATION
ACTIVITY 1.5.7: Swapping two variables.

Given x = 22 and y = 99. What are x and y after the given code?

1) >> x = y;
>> y = x; Correct

x is 99 and y is 22. x = y assigns 99 to x.


y = x then assign x's value, now 99, to y.
x is 22 and y is 99.
x is 99 and y is 99.

2) >> x = y;
>> y = x; Correct
>> x = y;
x = y assigns 99 to x.
x is 99 and y is 22. y = x then assign x's value, now 99, to y.
The last x = y assigns 99 to x.
x is 99 and y is 99.
x is 22 and y is 22.

3) >> tempVal = x;
>> x = y; Correct
>> y = x;
The last statement reads x's new value of 99 and assigns
x is 99 and y is 22. it to y. Instead, that statement should read tempVal.
x is 99 and y is 99.
4) >> tempVal = x;
>> x = y; Correct
>> y = tempVal;
The swap succeeds, because x's value is saved before
x is 99 and y is 22. being assigned 99, and then that saved value is assigned
to y.
x is 99 and y is 99.

Feedback?

CHALLENGE
ACTIVITY 1.5.1: Assigning a sum. 2/2

Assigning a sum
Write a statement that assigns numCoins with numNickels + numDimes.

Script   Save  Reset  MATLAB Documentatio

1 numNickels = 5
2 numDimes = 10
3
4 % Write a statement that assigns numCoins with numNickels + numDimes
5 numCoins=numNickels+numDimes

Previous Assessment: All Tests Passed

 Check if variables numNickels, numDimes, and numCoins exist

 Check numCoins' value

Output
numNickels =

numDimes =

10

numCoins =

15

Feedback?

CHALLENGE
ACTIVITY 1.5.2: Fahrenheit to Celsius using multiple statements. 2/2

Fahrenheit to Celsius using multiple statements


Given a Fahrenheit value temperatureFahrenheit, write a statement that assigns temperatureCelsius w
While the equation is C = 5/9 * (F - 32), as an exercise use two statements, the first of which is "fraction

Script   Save  Reset  MATLAB Documentatio

1 temperatureFahrenheit = 77
2
3 % Write a statement that assigns fractionalMultiplier with 5/9
4 fractionalMultiplier=5/9
5
6 % Modify the statement below to convert Fahrenheit to Celsius,
7 % assigning temperatureCelsius with the Celsius value
8 temperatureCelsius = fractionalMultiplier*(temperatureFahrenheit-32)
Previous Assessment: All Tests Passed

 Check if variables temperatureFahrenheit, fractionalMultiplier, and


temperatureCelsius exist

 Check if fractionalMultiplier is assigned with 5/9

 Check temperatureCelsius' value

Output

temperatureFahrenheit =

77

fractionalMultiplier =

0.5556

temperatureCelsius =

25

Feedback?

CHALLENGE
ACTIVITY 1.5.3: Multiple variables: Curving an exam score. 2/2

Multiple variables: Curving an exam score


Write a statement that assigns myExamScore with 82. Write a statement that assigns myCurvedExamS
Script   Save  Reset  MATLAB Documentatio

1 % Write a statement that assigns myExamScore with 82


2 myExamScore=82
3 % Write a statement that assigns myCurvedExamScore with myExamScore + 5
4 myCurvedExamScore=myExamScore+5

Previous Assessment: All Tests Passed (100%)

 Check if variables myExamScore and myCurvedExamScore exists

 Check myExamScore's value

 Check myCurvedExamScore's value

Output

myExamScore =

82

myCurvedExamScore =

87
Feedback?

How was this section?


 
Provide feedback

You might also like