%MA302
%script demonstrates input and output

%%
%Reading from files
%data_set1.txt - first example


fid0 = fopen('data_set1.txt');
if(fid0 ==-1)
    error('File open not successful')
else
    disp('File open successful')
end

%check data and notice that it has 4 columns

data_matrix = fscanf(fid0,'%d %d %d %d',[4,inf]);
%notice that data_matrix is the transpose!

%make sure the file has been closed.
closeresult = fclose(fid0);

if closeresult == 0
    disp('File close successful');
else
    error('File close not successful');
end

%%
%Writing matrix to a .dat file

M = randi([0 10],5,4);
fidw = fopen('randmat.dat','w');
fprintf(fidw,'%d %d %d %d \n',M);

closreresult = fclose(fidw);
if closeresult == 0
    disp('File close successful');
else
    error('File close not successful');
end

%Write to a .txt file
%open file
fid2 = fopen('myfile.txt','w');
if(fid2 <0)
    error('Could not open file "myfile.txt"');
end

for k=1:100
    fprintf(fid2,'Number = %d Square = %d \n',k,k*k);
end

%close
fclose(fid2);





