# Assignment statements,Errors,Floating-point arithmetic,comments in matlab

Posted by SUYOG PATIL on 6:17 PM in , , ,
Assignment statements
You can create your own variables, and give them values, with an assignment
statement. The assignment operator is the equals sign, =.
>> x = 6 * 7
x = 42
This example creates a new variable named x and assigns it the value of the
expression 6 * 7. MATLAB responds with the variable name and the computed
value.
In every assignment statement, the left side has to be a legal variable name.
The right side can be any expression, including function calls.
Almost any sequence of lower and upper case letters is a legal variable name.
Some punctuation is also legal, but the underscore, , is the only commonly used
non-letter. Numbers are fine, but not at the beginning. Spaces are not allowed.
Variable names are “case sensitive”, so x and X are different variables.
>> fibonacci0 = 1;
>> LENGTH = 10;
>> first_name = ’allen’
first_name = allen
The first two examples demonstrate the use of the semi-colon, which suppresses
the output from a command. In this case MATLAB creates the variables and
assigns them values, but displays nothing.
The third example demonstrates that not everything in MATLAB is a number.
A sequence of characters in single quotes is a string.Although i, j and pi are predefined, you are free to reassign them. It is common
to use i and j for other purposes, but it is probably not a good idea to change
the value of pi!

Why variables?
The most common reasons to use variables are
• To avoid recomputing a value that is used repeatedly. For example, if you
are performing computations involving e, you might want to compute it
once and save the result.
>> e = exp(1)
e = 2.7183
• To make the connection between the code and the underlying mathematics
more apparent. If you are computing the area of a circle, you might want
to use a variable named r:
>> r = 3
r = 3
>> area = pi * r^2
area = 28.2743
That way your code resembles the familiar formula πr2.
• To break a long computation into a sequence of steps. Suppose you are
evaluating a big, hairy expression like this:
ans = ((x - theta) * sqrt(2 * pi) * sigma) ^ -1 * ...
exp(-1/2 * (log(x - theta) - zeta)^2 / sigma^2)
You can use an ellipsis to break the expression into multiple lines. Just
type ... at the end of the first line and continue on the next.
But often it is better to break the computation into a sequence of steps
shiftx = x - theta
denom = shiftx * sqrt(2 * pi) * sigma
temp = (log(shiftx) - zeta) / sigma
exponent = -1/2 * temp^2
ans = exp(exponent) / denom
The names of the intermediate variables explain their role in the compu-
tation. shiftx is the value of x shifted by theta. It should be no surprise
that exponent is the argument of exp, and denom ends up in the denom-
inator. Choosing informative names makes the code easier to read and
understand.

Errors
It’s early, but now would be a good time to start making errors. Whenever you
learn a new feature, you should try to make as many errors as possible, as soon
as possible.
When you make deliberate errors, you get to see what the error messages look
like. Later, when you make accidental errors, you will know what the messages
mean.
A common error for beginning programmers is leaving out the * for multiplica-
tion.
>> area = pi r^2
??? area = pi r^2
|
Error: Unexpected MATLAB expression.
The error message indicates that, after seeing the operand pi, MATLAB was
“expecting” to see an operator, like *. Instead, it got a variable name, which is
the “unexpected expression” indicated by the vertical line, | (which is called a
“pipe”).
Another common error is to leave out the parentheses around the arguments of
a function. For example, in math notation, it is common to write something
like sin π, but not in MATLAB.
>> sin pi
??? Function ’sin’ is not defined for values of class ’char’.
The problem is that when you leave out the parentheses, MATLAB treats the
argument as a string (rather than as an expression). In this case the sin function
generates a reasonable error message, but in other cases the results can be
baffling. For example, what do you think is going on here?
>> abs pi
ans = 112 105
There is a reason for this “feature”, but rather than get into that now, let me
suggest that you should always put parentheses around arguments.
This example also demonstrates the Second Theorem of Debugging:
The only thing worse than getting an error message is not getting
an error message.
Beginning programmers hate error messages and do everything they can to make
them go away. Experienced programmers know that error messages are your
friend. They can be hard to understand, and even misleading, but it is worth
making some effort to understand them.
Here’s another common rookie error. If you were translating the following math-
ematical expression into MATLAB:
1
2pπ
You might be tempted to write something like this:
1 / 2 * sqrt(pi)
But that would be wrong. So very wrong.

Floating-point arithmetic
In mathematics, there are several kinds of numbers: integer, real, rational,
irrational, imaginary, complex, etc. MATLAB only has one kind of number,
called (for reasons I won’t explain here) floating-point.
You might have noticed that MATLAB expresses values in decimal notation.
So, for example, the rational number 1/3 is represented by the floating-point
value
>> 1/3
ans = 0.3333
which is only approximately correct. It’s not quite as bad as it seems; MATLAB
uses more digits than it shows by default. You can change the format to see
the other digits.
>> format long
>> 1/3
ans = 0.33333333333333
Internally, MATLAB uses the IEEE double-precision floating-point format,
which provides about 15 significant digits of precision (in base 10). Leading
and trailing zeros don’t count as “significant” digits, so MATLAB can represent
large and small numbers with the same precision.
Very large and very small values are displayed in scientific notation.
>> factorial(100)
ans = 9.332621544394410e+157
The e in this notation is not the transcendental number known as e; it is just an
abbreviation for “exponent”. So this means that 100! is approximately 9.33 ×
10157. The exact solution is a 158-digit integer, but we only know the first 16
digits.
You can enter numbers using the same notation.
>> speed_of_light = 3.0e8
speed_of_light = 300000000
Although MATLAB can handle large numbers, there is a limit. The predefined
variables realmax and realmin contain the largest and smallest numbers that
MATLAB can handle†.
>> realmax
ans = 1.797693134862316e+308
>> realmin
ans = 2.225073858507201e-308
If the result of a computation is too big, MATLAB “rounds up” to infinity.
>> factorial(170)
ans = 7.257415615307994e+306
>> factorial(171)
ans = Inf
Division by zero also returns Inf, but in this case MATLAB gives you a warning
because in many circles division by zero is considered undefined.
>> 1/0
Warning: Divide by zero.
ans = Inf
A warning is like an error message without teeth; the computation is allowed to
continue. Allowing Inf to propagate through a computation doesn’t always do
what you expect, but if you are careful with how you use it, Inf can be quite
useful.
For operations that are truly undefined, MATLAB returns NaN, which stands
for “not a number”.
>> 0/0
Warning: Divide by zero.
ans = NaN

Along with the commands that make up a program, it is useful to include
language. The percent symbol % separates the comments from the code.
>> speed_of_light = 3.0e8 % meters per second
speed_of_light = 300000000
The comment runs from the percent symbol to the end of the line. In this case
it specifies the units of the value. In an ideal world, MATLAB would keep track
of units and propagate them through the computation, but for now that burden
falls on the programmer.
Comments have no effect on the execution of the program. They are there
Avoid comments that are redundant with the code:
>> x = 5 % assign the value 5 to x
Good comments provide additional information that is not in the code, like
units in the example above, or the meaning of a variable:
>> p = 0 % position from the origin in meters
>> v = 100 % velocity in meters / second
>> a = -9.8 % acceleration of gravity in meters / second^2
If you use longer variable names, you might not need explanatory comments,
but there is a tradeoff: longer code can become harder to read. Also, if you are
translating from math that uses short variable names, it can be useful to make