3
\$\begingroup\$

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.

200_success
146k22 gold badges190 silver badges479 bronze badges
asked Apr 6, 2015 at 20:46
\$\endgroup\$
0

1 Answer 1

2
\$\begingroup\$

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.

answered May 15, 2015 at 4:28
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.