Displaying/Saving Results
There are several ways to display the values of variables in the command window.
To change the format of the values when they are displayed in the command window use the format command.
One can also change this format from the Preferences dialog that appears when the File/Preferences item
is selected in the GUI.
To write variables to a file use the fprintf command.
One can also record all activity in a matlab session by using diary command.
Samples
% displaying the internal value of pi
pi
ans =
3.1416
% displaying the value after resetting the format
format long e
pi
ans =
3.141592653589793e+000
% displaying the value using sprintf
sprintf('%10.8f \n',pi)
ans =
3.14159265
% generate some x,y data and then save it to the file results.txt
x = 0.0:.2:1.0;
y = sin(x);
fid = fopen('results.txt','w'); % open the file for writing (overwriting existing data)
fprintf(fid,'%10.5f ',x); % print out the x values (fprintf knows about vectors)
fprintf(fid,'\n'); % print a linefeed
fprintf(fid,'%10.5f ',y); % print out the y values
fclose(fid); % close the file
type results.txt
0.00000 0.20000 0.40000 0.60000 0.80000 1.00000
0.00000 0.19867 0.38942 0.56464 0.71736 0.84147
% generate some x,y data and then save it to the file results.txt
% in column format
x = 0.0:.2:1.0;
y = sin(x);
dataOut = [x;y]; % create a matrix to hold data as columns
fid = fopen('results.txt','w'); % open file (overwriting existing data)
fprintf(fid,'%10.5f %10.5e \n',dataOut); % write data x in fixed point, y in exponential format
fclose(fid); % close file
type results.txt
0.00000 0.00000e+000
0.20000 1.98669e-001
0.40000 3.89418e-001
0.60000 5.64642e-001
0.80000 7.17356e-001
1.00000 8.41471e-001
%
% An example showing how to print out several values in one row
%
iter= 5;
x = 3.0;
y = 2.0;
e = 5.0;
v = [iter,x,y,e]; % put the values in a vector
sprintf('%4d %10.5e %10.5e %10.5e \n',v) % use formatted output
ans =
| UCLA Mathematics Department | ©2000 |