%matlab create and read file examples
%ex 1
disp("ex 1")
%Create a sample text file that contains floating-point numbers.
x = 100*rand(8,1);
fileID = fopen('nums1.txt','w');
fprintf(fileID,'%4.4f\n',x);
fclose(fileID);
%View the contents of the file.
type nums1.txt
%Open the file for reading, and obtain the file identifier, fileID.
fileID = fopen('nums1.txt','r');
%Define the format of the data to read. Use '%f' to specify floating-point numbers.
formatSpec = '%f';
%Read the file data, filling output array, A, in column order. fscanf reapplies the format, formatSpec, throughout the file.
A = fscanf(fileID,formatSpec)
%Close the file.
fclose(fileID);
pause

%-- ex 2
disp("ex 2")
%Create a sample text file that contains integers and floating-point numbers.
x = 1:1:5;
y = [x;rand(1,5)];
fileID = fopen('nums2.txt','w');
fprintf(fileID,'%d %4.4f\n',y);
fclose(fileID);
%View the contents of the file.
type nums2.txt
%Open the file for reading, and obtain the file identifier, fileID.
fileID = fopen('nums2.txt','r');
%Define the format of the data to read and the shape of the output array.
formatSpec = '%d %f';
%Read the file data, filling output array, A, in column order. fscanf reuses the format, formatSpec, throughout the file.
A = fscanf(fileID,formatSpec) %not quite what we want
sizeA = [2 Inf];
A = fscanf(fileID,formatSpec,sizeA) %better
fclose(fileID);
%Transpose the array so that A matches the orientation of the data in the file.
A = A'
pause

%ex 3
% specific characters in a sample file, and return only numeric data.
%Create a sample text file containing temperature values.
str = '78°C 72°C 64°C 66°C 49°C';
fileID = fopen('temperature.dat','w');
fprintf(fileID,'%s',str);
fclose(fileID);
%Read the numbers in the file, skipping the text, °C. Also return the number of values that fscanf reads. The extended ASCII code 176 represents the degree sign.
fileID = fopen('temperature.dat','r');
degrees = char(176); %ascii for the degree sign
[A,count] = fscanf(fileID, ['%d' degrees 'C'])
fclose(fileID);
%A is a vector containing the numeric values in the file. count indicates that fscanf read five values.