how to output how many numbers in the range are prime numbers using the function that i created?

1 view (last 30 days)
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 Comment
Stephen23
Stephen23 on 27 Nov 2015
Edited: Stephen23 on 27 Nov 2015
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
  1. one script
  2. one or more functions
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.

Sign in to comment.

Answers (2)

Thorsten
Thorsten on 27 Nov 2015
Edited: Thorsten on 27 Nov 2015
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

Stalin Samuel
Stalin Samuel on 27 Nov 2015
Check this
  2 Comments
Bjorn Gustavsson
Bjorn Gustavsson on 27 Nov 2015
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.

Sign in to comment.

Products

Community Treasure Hunt

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

Start Hunting!