Mathlab assignment: Write a MATLAB code using \'fopen\', \'fprintf\', \'fscanf\'
ID: 2085592 • Letter: M
Question
Mathlab assignment:
Write a MATLAB code using 'fopen', 'fprintf', 'fscanf', and 'fclose' to create a text file that contains the following (notice the space between the different characters and numbers): x y z 1 4 5 3 6 8 Then, without loosing the contents of the file, append a row of three numbers to the file: 4 7 9 Then, read the contents of the file as follows. First, read the first three characters (i.e., 'x', 'y', 'z') as strings using 'fscanf' and '%s' for formatting, and the remaining as integers using again 'fscanf' and '%d' for formatting. Print to the command prompt what is read from the file, using ‘fprint’, to make sure that it was read properly.
Explanation / Answer
%First create & open the file with permission to write discarding any previous content.
%Hence 'w'
file_id=fopen('text file.txt', 'w');
%now enter the string to file as mentioned in the question
fprintf(file_id, 'x y z 1 4 5 3 6 8 ');
%then close the file
fclose(file_id);
%now again open the file with the permission to append to the end of the
%existing data with 'a'
file_id=fopen('text file.txt', 'a');
%now append the data as mentoned in the question
fprintf(file_id, '4 7 9');
%then close the file
fclose(file_id);
%now read from the file
file_id=fopen('text file.txt', 'r');
%now read the characters one by one & display
data=fscanf(file_id, ['%s' '%s' '%s' '1' '4' '5' '3' '6' '8' '4' '7' '9'])
%then again open the file & read the numbers
file_id=fopen('text file.txt', 'r');
data1=fscanf(file_id, 'x y z %d %d %d %d %d %d %d %d %d');
%now close the file
fclose(file_id);
If any doubt or clarification needed, please let me know in the comments.
Please leave a thumbs up.