Practice in MATLAB
- Practice problem 1: Edit buggy.m so that when it runs, it produces this output in
the Command Window:
>> buggy
ans =
3
ans =
120
ans =
5
ans =
57
ans =
2
ans =
3125
Warning: Divide by zero.
> In buggy at 13
ans =
Inf
ans =
3.1416
ans =
314.1593
ans =
3.1416e+03
ans =
0
ans =
71.3208
Welcome to CS112
>>
- Practice problem 2: Create a new file called test.m.
We're going to work with 3 different values:
- 2π2
- √2
- (0.000001234 + 5.67 × 10-3) × 0.4567 × 10-4
Write test.m so that it produces output exactly like this:
>> test
This is the start of my program
ans =
19.7392
The square root of 2 is
ans =
1.4142
ans =
2.5901e-07
The square root of 1010101 is
1.005e+03
This is the end of my program
>>
Note that you can change the format of the numbers by using
format long to produce this output:
>> test
This is the start of my program
ans =
19.73920880217872
The square root of 2 is
ans =
1.41421356237310
ans =
2.590052567800000e-07
The square root of 1010101 is
1.005037810234023e+03
This is the end of my program
**Challenge: Change the 'square root of
1010101' output in the box above (the 3rd to last line) so that the text and value are displayed on the same
line like this: The square root of 1010101 is 1005.0378
Notes:
- Inserting disp statements in your code can help
pinpoint the location of bugs in your scripts (you can always remove the excess
disp statements after your code works perfectly).
- clc clears the Command Window, which some
people like when running their code
- Fastest way to re-run a script? Double-click on the name of the script
in the Command History window (if you like the mouse) or hit the "up-arrow" key (if you prefer the keyboard) to yank back the last command, and then hit return.
- A semicolon ; suppresses output. Try
adding semicolons at the end of a few lines in your
test.m. Run test.m and note the difference in the Command
Window. (Today we are not producing a lot of output, but in the future,
the semicolon will come in handy).
|