Calculate the value of x entered in function(2) using function(1). How to link the two functions ?

Hi, I'm new to Matlab. I was asked to write a function that tests for prime numbers. The user enters the value of x then the program decides whether it's prime or not. Here's the function:
x=input('Enter an integer ');
%Trick: prime numbers are larger than 1, whole numbers, and not even.
%mod(x,2) == 0 , tests for even numbers.
%rem(x,1)~=0 , tests for non-whole numbers.
if x<=1 || mod(x,2) == 0 || rem(x,1) ~= 0
disp('0'); % x is not a prime number.
else
isprime(x)
end
I then was asked to write another function that allows the user to enter a range of x values and then the function finds all the prime numbers in that range. To do this I have to link the second function with the first function above. Meaning the calculation to test a number whether it's prime or not have to be done in the first function. I heard of structures but I don't know how/when to use them. This is my incomplete code for the second function. I don't know how to link these two functions together !!
I just want to run the if statement from function(1) using the values of x from function(2) without copying the if statement to function(2). i.e calling it from function(1)
lower=input('Enter the lower value of the range');
upper=input('Enter the upper value of the range');
L= ceil(lower);
U= floor(upper);
x=[L:1:U]

Answers (1)

lower=input('Enter the lower value of the range = ');
upper=input('Enter the upper value of the range = ');
x = lower:upper;
out = x(isprime(x))
OR
old answer
function p = findprimes(m,n)
p = [];
for j = m:n
if j-nnz(rem(j,1:j)) == 2
p = [p;j];
end
end

1 Comment

see http://www.mathworks.com/matlabcentral/answers/5195-i-need-to-write-a-function-which-prints-out-prime-number-between-the-two-arguments

Sign in to comment.

Products

Tags

Asked:

on 17 Apr 2012

Community Treasure Hunt

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

Start Hunting!