필터 지우기
필터 지우기

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
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
  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.

댓글을 달려면 로그인하십시오.

답변 (2개)

Thorsten
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

Stalin Samuel
Stalin Samuel 2015년 11월 27일
Check this
  댓글 수: 2
Natalia Wong
Natalia Wong 2015년 11월 27일
i am not allowed to use isprime i have already created my own function to determine prime number
Bjorn Gustavsson
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 CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by