Plot σx vs. r(Take 3: File Input/Output)

Read in [A] from a file


Read in [B] from the same file

Note that the following video contains a part where the text file is read into Excel. This is only for illustration purposes (to check the range that we need to feed into the dlmread function). The data is still read from the .txt file, so you can skip following the Excel steps and just watch these steps being done in the video.


Output Values Using dlmwrite

Just as you can read in values from a text file to a matrix, you can also write a matrix to a text file. The function for this is called dlmwrite. Consider the following syntax:

And the following example:

We write matrix A to a text file named output_file, and we use a space as a delimiter. Add this line of code to beam4.m and run it. You should see a text file named output_file appear in your working directory. If you wish to learn more about dlmwrite, use your best friend...documentation!

Output Important Values Using fprintf

Another function that can be used to save important values is fprint f. Suppose we are asked to report the numerical values of the bending stress for inner radius =0.5, 1.0, and 1.5 cm. These values are already contained in the vectors "ri" and "sigma_x".

The "fprintf" command is useful for outputting information to the command window. You can include both text and numbers in your output and choose the precision of the numbers to match your needs. Look up "fprintf" in the documentation for more information. 

The basic form is as follows:

fprintf('String with references to variables\n', variables)

The "\n" starts a new line at that point in the statement. Let's take a simple example. Suppose you want to output a number and a percentage with text in between. The variable "sp" is found to be 0.962 and the variable "year" is 2005. Since 2005 is a whole number, this is easy to output using "fprintf" by using "%d". If you are using a decimal number or one that may be inexact, like the percentage, then use "%f". If you put numbers and a decimal between the % and the f, you can control how many number spaces there are before and after the decimal. Let's try it with our example.

>> sp = 0.962;

>> year = 2006;

>> fprintf('In %d, Dave McKee had a %2.2f save percentage playing for Cornell.\n\n', year, sp*100)

This will return the following in the command window:

In 2006, Dave McKee had a 96.20 save percentage playing for Cornell.

Notice that we can perform arthimetic operations in the output section and specify the number of decimals to be 2. Also notice that "\n" switches to a new line and "\t" will produce an indent.

The same concept can be used to output the bending stress sigma_x when ri= 1 cm. Try this command out.

fprintf('When ri = %3.2f cm, ',1e2*ri(6));
fprintf('sigma_x = %3.2f MPa\n',sigma_x(6));

Go to Step 6: Plot σx vs. r(Take 4: Functions)

Go to all MATLAB Learning Modules

  • No labels