MATLAB for File Input and Output


Introduction

MATLAB provides powerful tools for reading data from files and writing data to files. In this guide, we'll introduce you to file input and output in MATLAB with sample code and examples.


Reading from Text Files

You can read data from text files using functions like textread or importdata. Here's how you can read data from a text file:

% Example: Reading from a text file
data = textread('data.txt', '%f');

Writing to Text Files

To write data to a text file, you can use functions like fwrite or simply use the fprintf function to format and write data.

% Example: Writing to a text file
data = [1, 2, 3, 4, 5];
fileID = fopen('output.txt', 'w');
fprintf(fileID, '%d\n', data);
fclose(fileID);

Reading and Writing Binary Files

MATLAB also allows you to read and write binary files using functions like fread and fwrite.

% Example: Reading and writing binary files
data = rand(3, 3);
fileID = fopen('binary_data.bin', 'wb');
fwrite(fileID, data, 'double');
fclose(fileID);
fileID = fopen('binary_data.bin', 'rb');
loaded_data = fread(fileID, [3, 3], 'double');
fclose(fileID);

Working with Excel Files

You can read and write data to Excel files using functions like xlsread and xlswrite. Make sure you have the Excel file in the current working directory.

% Example: Working with Excel files
data = xlsread('data.xlsx');
xlswrite('output.xlsx', data);

Conclusion

MATLAB's file input and output capabilities allow you to interact with a wide range of data formats. Whether you're working with text files, binary files, or Excel files, MATLAB provides the tools you need to read and write data effectively.


Enjoy using MATLAB for file input and output in your data processing and analysis tasks!