4. Plotting, Data Visualization, and File I/O
MATLAB is renowned for its excellent plotting capabilities, allowing you to visualize data effectively. It also provides robust tools for managing data persistence through file input/output.
4.1. 2D and 3D Plotting Basics
Create various types of plots with simple commands:
- 2D Plots:
plot,scatter,bar.x = 0:0.1:2*pi; y = sin(x); plot(x, y, 'b--o'); % Blue dashed line with circles xlabel('X-axis'); ylabel('Y-axis'); title('Sine Wave Plot'); legend('sin(x)'); grid on; - Multiple Plots: Use
hold onto add more data to an existing plot.hold on; plot(x, cos(x), 'r:x'); % Red dotted line with 'x' markers hold off; - 3D Plots:
plot3,surf,mesh.[X,Y] = meshgrid(-2:.2:2); Z = X .* exp(-X.^2 - Y.^2); surf(X,Y,Z); colorbar;
4.2. File Input/Output
MATLAB offers functions to read and write data from/to files.
- MAT-files: MATLAB\'s native format for saving/loading Workspace variables.
data = [1 2 3; 4 5 6]; save('mydata.mat', 'data'); % Saves 'data' variable to mydata.mat clear data; load('mydata.mat'); % Loads 'data' back into Workspace - CSV files: Common format for tabular data.
writematrix(data, 'output.csv'); loaded_data = readmatrix('output.csv'); - Text files: For custom text file formats.
fileID = fopen('log.txt', 'w'); % Open for writing fprintf(fileID, 'Processing complete at %s\n', datestr(now)); fclose(fileID);
Key Concept: Effective visualization makes complex data understandable, and reliable file I/O ensures your data is persistent and exchangeable.