how to output how many numbers in the range are prime numbers using the function that i created?
5 次查看(过去 30 天)
显示 更早的评论
function[ result ] = MyPrime( X );
this is my function how do i input an array to the input argument which is X and output how many prime numbers are there in the range and list them? thanks I am new to MATLAB
1 个评论
Stephen23
2015-11-27
编辑:Stephen23
2015-11-27
What you have written is not a function because it does not start with the function operator. It is actually a script. You can read about the different between scripts and functions in the documentation. One MATLAB M-file can contain either
It is not possible to mix the two: a file either is a script, or has functions, but cannot have both. I would recommend that you learn to write code using functions, which have many advantages over scripts.
回答(2 个)
Thorsten
2015-11-27
编辑:Thorsten
2015-11-27
I have correct the code and made several remarks; if you call the function without argument X, the user is asked to input the range. Then the user has to type the brackets [ ] around the input, like [10 20].
function theprimes = MyPrime( X ) % use keyword function to define a function
% rename results to theprimes
if nargin == 0 % user input of range if no argument is supplied to function
X = input('Enter a range of numbers: ');
end
m = 1;
theprimes = []; % initialize return value
for i = X(1):X(end) % :1: is the default, not necessary, and ; is not needed here
%k=mod(i,1:i);
%zero=find(k==0);
%n_zero=length(zero);
%if n_zero==2 % no ; needed here
% instead of the above 4 lines, you could also use the nnz function and no extra variables
if nnz(mod(i,1:i) == 0) == 2
theprimes(m)=i; % use function return value theprimes here
m=m+1;
end
% i=i+1; % that's wrong, i is incremented in the for loop already
end
c=numel(theprimes);
if c == 0 % NOT theprimes==0; if isempty(theprimes) would also work
fprintf('There are no prime numbers\n')
else
fprintf('There are %0.d prime numbers and they are ', c);
fprintf(' %d',theprimes) % use theprimes, not c
end
0 个评论
Stalin Samuel
2015-11-27
2 个评论
Bjorn Gustavsson
2015-11-27
Well the problem you have is twofold.
1, you have not written a function MyPrime since you seem to have put that code in the script task2.m, the function-file should start with a line:
function [res] = MyPrime(X)
which should be followed by the code in your script where you check whether the number is a prime. 2, Then you'll have to clean up the script.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!