# Dealing with input and output in Matlab

I just wrote a program which performed some elementary set operations as you can see below. It's the first time I have used input and output of text files so I am mainly looking for critique on that, and also how I use cells.

clear all;
clc;

fileID = fopen('inputseto.txt','r');
data = textscan(fileID,'%s',3,'Delimiter','\n');
data = data{1,1};

n = data{1}
n = str2num(n);

A = data{2};
B = data{3};

A = str2num(A(2:end-1));
B = str2num(B(2:end-1));

output = cell(1,6);

output{1} = union(A,B);
output{2} = intersect(A,B);
output{3} = setdiff(A,B);
output{4} = setdiff(B,A);
output{5} = setdiff(1:n,A);
output{6} = setdiff(1:n,B);

fileID = fopen('outputseto.txt','w');

for i = 1:6
fprintf(fileID,'{');
fprintf(fileID,'%d, ',output{i}(1:end-1));
if i ~= 6
fprintf(fileID,'%d}\n',output{i}(end));
else
fprintf(fileID,'%d}',output{i}(end));
end
end


I got this problem from here. The input is 3 lines, the first lines describes the global set. The first line is an integer n and the global set is the set containing 1,2,...,n. Then the next two lines are two sets A and B. The output consists of various set operations involving A and B. The solution is correct, but I feel like some of this code doesn't "feel right". I am interested in knowing what you think.

The only thing that I see is that the files are not closed with fclose after the data is read/written. Especially using the same variable (fileID) as the file handle for the second while the first is still open (effectively losing the first one). Although you can still always do fclose('all') and I think it would close even those files still open that don't have a handle still assigned.