removing non prime number function
조회 수: 1 (최근 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."
댓글 수: 0
답변 (2개)
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);
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Denoising and Compression에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!