removing non prime number function
2 views (last 30 days)
Show older comments
I am trying to create a function that removes nonprime numbers from a file. My file is
integersB.txt:
11
2
3
709
303
288
15
1625
987
and here is my function:
function rid_of_nonprimes
fid = fopen('integersB.txt', 'r');
wtf = [];
if fid == -1
disp('File not opened successfully')
else
numgroup = textscan(fid, '%d');
numgroup = cell2mat(numgroup);
for i = 1:length(numgroup)
if isprime(numgroup(i))
wtf = [wtf;numgroup(i)];
end
end
end
closer = fclose(fid);
if closer == 0
disp('File successfully closed')
else
disp('File NOT closed')
end
fid2 = fopen('integersB.txt', 'w');
for j = 1:length(wtf)
fprintf(fid2, '%d\n', wtf(j));
end
closer2 = fclose(fid2);
if closer2 == 0
disp('File successfully closed')
else
disp('File NOT closed')
end
end
When I go to the command window:
>> fid = fopen('integersB.txt', 'r')
fid =
11
>> fid2 = fopen('integersB.txt', 'w')
fid2 =
12
>> rid_of_nonprimes
File successfully closed
File successfully closed
When I run the function in the command window, all I get is 2 "file successfully closed."
0 Comments
Answers (2)
Stephen23
on 8 Nov 2019
str = fileread('temp.txt');
vec = str2double(regexp(str,'\d+','match'))
[fid,msg] = fopen('output.txt','wt');
assert(fid>=3,msg)
fprintf(fid,'%d\n',vec(isprime(vec)));
fclose(fid);
0 Comments
See Also
Categories
Find more on Denoising and Compression in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!