How to Append Data to a File in MATLAB?
Last Updated :
21 Sep, 2022
Appending data to a text file means adding data to a file that already exists in the storage. print() function is used to write/append data to a file in MATLAB. It writes formatted text to a file based on the format string provided to it. The format of the output/input is determined by the formatting specifier.
A format specifier is used to format ordinary text and special characters. It starts with a percent sign % and ends with a conversion sign. The different format specifiers used within fprintf function are:
%d : Display the value as an integer
%e : Display the value in exponential format
%f : Display floating point number
%g : Display the value with no trailing zeros
%s : Display string array (Unicode characters)
%c : Display single character(Unicode character)
Escape sequences used with fprintf function are:
\n : create a new line
\t : horizontal tab space
\v : Vertical tab space
\r : carriage return
\\ : single backslash
\b : backspace
%% : percent character
Now before adding/appending data to a file, we have to ensure that the file exists. For that we will check whether the file exists or not using isfile function:
Example 1:
Matlab
filename = "Geeks.txt" ;
if isfile(filename)
else
|
On the basis of the above control structure, we can add data to the file if it exists, or display an error if it doesn’t. Be aware that isfile searches for the given filename within the Current Working Directory of the MATLAB program. i.e. the file should exist in the same directory as the program.
For file R/W operation we would be using the aforementioned fprintf function. Since MATLAB is predominantly used for operations performed over matrices, we would be appending a matrix to a file containing data regarding other matrices.
The file named Geeks.txt contains the following data:
we would be appending the following matrix to the file:
a = [7, 8, 9]
Example 2:
Matlab
filename = "Geeks.txt" ;
a = [7, 8, 9]
if isfile(filename)
fid = fopen(filename, 'a+' );
fprintf(fid, '\n%3d %3d %3d' , a);
fclose(fid);
else
disp( "Error! File doesn't exist" );
end
|
Output:
Explanation:
In the above code firstly the name of the file is saved into the variable filename. Then a 1D array was defined that is to be appended inside the file. After which the presence of the file is tested using the isfile function. If the file exists, then the file is opened via fopen function in append mode (using a+ flag) and its descriptor is saved into variable fid. Then the file descriptor, format string denoting the array (padding included) and the array to be appended is passed as an argument to the function. In the end, the file is closed. If the file doesn’t exist isfile equates to 0, and else the block is executed. Resulting in an error message being displayed.
Note:
- It is possible that the file may not open even if it is present, due to file locks, unauthorized access, low memory space, etc. In that case, the file descriptor will have the value -1 assigned to it, which could be checked to determine whether the file got opened or not (using an if statement).
- The second argument to the fopen function is a+ which tells the compiler that this file is to be opened in append mode. Other modes include read, write, binary, etc.
- The format specifier is based solely on what type of data is being appended to the file. In the case of strings, it would be %s for floating values it would be %f, etc. So an understanding of format strings is required to properly append data into the files.
Similar Reads
Non-linear Components
In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Class Diagram | Unified Modeling Language (UML)
A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Spring Boot Tutorial
Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Backpropagation in Neural Network
Backpropagation is also known as "Backward Propagation of Errors" and it is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network. In this article we will explore what
10 min read
AVL Tree Data Structure
An AVL tree defined as a self-balancing Binary Search Tree (BST) where the difference between heights of left and right subtrees for any node cannot be more than one. The absolute difference between the heights of the left subtree and the right subtree for any node is known as the balance factor of
4 min read
3-Phase Inverter
An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read
What is Vacuum Circuit Breaker?
A vacuum circuit breaker is a type of breaker that utilizes a vacuum as the medium to extinguish electrical arcs. Within this circuit breaker, there is a vacuum interrupter that houses the stationary and mobile contacts in a permanently sealed enclosure. When the contacts are separated in a high vac
13 min read
Polymorphism in Java
Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read
Random Forest Algorithm in Machine Learning
A Random Forest is a collection of decision trees that work together to make predictions. In this article, we'll explain how the Random Forest algorithm works and how to use it. Understanding Intuition for Random Forest AlgorithmRandom Forest algorithm is a powerful tree learning technique in Machin
7 min read
What is a Neural Network?
Neural networks are machine learning models that mimic the complex functions of the human brain. These models consist of interconnected nodes or neurons that process data, learn patterns, and enable tasks such as pattern recognition and decision-making. In this article, we will explore the fundament
14 min read