removing non prime number function

5 Ansichten (letzte 30 Tage)
Britnie Casillas
Britnie Casillas am 8 Nov. 2019
Bearbeitet: Bhaskar R am 8 Nov. 2019
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."

Antworten (2)

Bhaskar R
Bhaskar R am 8 Nov. 2019
Bearbeitet: Bhaskar R am 8 Nov. 2019
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 am 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);

Kategorien

Mehr zu Denoising and Compression finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by