Calculate for using an increment of .
for x=-pi:pi/4:pi y=cos(x); fprintf('%8.3f %8.2f nn',x,y); end
In the brief script above, x is the loop index that is initiated from and incremented with to a final value of . At the end of each increment, is calculated and displayed with the fprintf command. This process continues until .
From a previous exercise we know \n creates a new line when included in the fprintf command. Here, we also use %8.3f to specify eight spaces and three decimal places for the first variable x. Likewise %8.2f specifies the formatting for the second variable y but in this case, y is displayed with two decimal places. The result is the following:
-3.142 -1.00 -2.356 -0.71 -1.571 0.00 -0.785 0.71 0.000 1.00 0.785 0.71 1.571 0.00 2.356 -0.71 3.142 -1.00
We can improve our code by adding formatting lines as follows:
clear; clc; fprintf(' x cos(x)nn') % title row fprintf(' ----------------nn') % title row for x=-pi:pi/4:pi % loop_index=inital_value:increment_value:final_value y=cos(x); % code to calculate cos(x) fprintf('%8.3f %8.2f nn',x,y); % code to print the output to screen end
Screen output:
x cos(x) ---------------- -3.142 -1.00 -2.356 -0.71 -1.571 0.00 -0.785 0.71 0.000 1.00 0.785 0.71 1.571 0.00 2.356 -0.71 3.142 -1.00
- 瀏覽次數:1226