removing non prime number function

2 次查看(过去 30 天)
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."

回答(2 个)

Bhaskar R
Bhaskar R 2019-11-8
编辑:Bhaskar R 2019-11-8
In short your function, assuming you have the data format as you mentioned
data = textread(' integersB.txt', '%d');
prime_numbers = data(isprime(data));

Stephen23
Stephen23 2019-11-8
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);

类别

Help CenterFile Exchange 中查找有关 Denoising and Compression 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by