Spring 2001 CS100M Solutions to Exercise E2
Remarks
Recall the steps to perform an assignment lhs=rhs in Matlab:
+ Evaluate $lhs$ to determine a location.
+ Evaluate $rhs$ to determine a value
(the value of a variable $v$ is its current value.)
+ If $lhs$ does not exist, then declare it as a new variable.
(Declare means create a new named box to hold values.)
+ Place the value into the location,
replacing whatever value used to be in the location.
Observe that according to these rules, if $x$ and $y$ are different
variables, then after $x=y$ is performed, modifying $y$ has NO effect
on the value of $x$.
NOTE: the 2nd and 3rd steps above were originally in the wrong order here and in 1/25 lecture notes.
Note: This sentence shows how crossing out looks for numbers: it should appear crossed out, or at least italicized. Crossed out vectors and structs are shown with a gray background.
1.
w | | | 1 | | | | | | | 8 | | | | | | | 64 | | | | | | | 512 | | | | | |
x | | 3 | | | | | | | 1 | | | | | | | 4 | | | | | | | 6 | | | | | | |
y | | | | 2 | | | 7 | | | | 2 | | | 7 | | | | 2 | | | 7 | | | | 2 | | | 7 | |
z | 1 | | | | 3 | 1 | | 8 | | | | 24 | 8 | | 64 | | | | 192 | 64 | | 512 | | | | 1536 | 512 | | 4096 |
2.
genny |
|
|
| entire struct crossed out | |
3.
x |
|
|
|
| entire vector crossed out | entire vector crossed out | |
Here are all the updates, listed in order (not required of you;
provided in case you find it helpful):
x = 5 1 4 8 2 6 3 9 7
i = 3
j = 1
i = 5
x(5) = 3
j = 2
i = 4
x(4) = 9
j = 3
i = 10
x = 5 1 4 9 3 6 3 9 7 3 <-- entire vector gets replaced
j = 4
i = 4
x(4) = 10
j = 5
i = 11
x = 5 1 4 10 3 6 3 9 7 3 5 <-- entire vector gets replaced
[2/02] TIPS
+ draw a variable as the name next to the box for its value
+ draw values inside or nearby the box for a variable
+ all fields of a struct should be inside the box,
but you are allowed to extend the box, e.g. $x.a=5$
might look like this:
+------+ +---+
x | a[5] | but not x.a | 5 |
+------+ +---+
and then after also executing $x.b=7$, you could have
+------+ +------+ +---+ +---+
x | a[5] | or x | a[5] | but not x.a | 5 | x.b | 7 |
+------+ | | +---+ +---+
| b[7] | | b[7] |
+------+ +------+
+ cross out, not scribble out, old values
+ for structs and vectors, if the whole thing is replaced,
then the whole value gets crossed out.
e.g. continuing the example above,
if we next execute $x=0$, then you could have:
+-------+ +---------+
x | a[5/] | x | a[5/] |
| / | | / 0 |
| b/[7] | 0 or | b/[7] |
| / | | / |
+-------+ +---------+