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 =
15
ans =
57
ans =
2
ans =
3125
ans =
Inf
ans =
3.1416
ans =
314.1593
ans =
3.1416e+03
ans =
0
ans =
71.3208
Welcome to CS112
The square root of 853 is
ans =
29.2062
>>
- Practice problem 2: Create a new file called product.m (make sure it is in your lab1 folder).
In this file, display your name, and then the product of the numbers 1 through 10.
- Practice problem 3: Create a new file called hello.m (in your lab1 folder).
We're going to work with 3 different values (the italics are the English description of the values):
- 2π2 (2 times the quantity Pi squared)
- √2 (the square root of 2)
- (0.000001234 + 5.67 × 10-3) × 0.4567 × 10-4 (some hairy number)
Write hello.m so that it produces output exactly like this:
>> hello
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:
>> hello
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
hello.m. Run hello.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).
Practice problem 4: Save the file
byggy.m you
worked with in Problem 1 as first.m.
Run it to make sure it contains no errors.
Update the top of the file comments.
Then make the necessary changes to first.m so, when you run it,
it produces this output:
|