177k views
4 votes
Create a MATLAB function called isprime that checks if a number is prime using a for loop (Do not use the built-in MATLAB function isprime). The function takes one input argument which is a number and returns true if the number is prime and false if it is not.

User Vivek Maru
by
7.9k points

1 Answer

4 votes

Answer:

Step-by-step explanation:

Here's the code for the isprime function in MATLAB:

```

function result = isprime(n)

if n <= 1

result = false;

return;

end

for i = 2:sqrt(n)

if mod(n, i) == 0

result = false;

return;

end

end

result = true;

end

```

This function first checks if the input number is less than or equal to 1, which is not a prime number. If it is, then the function returns false.

Next, the function uses a for loop to check if the input number is divisible by any number between 2 and the square root of the input number. If the input number is divisible by any of these numbers, then the function returns false. Otherwise, the function returns true.

You can call this function by typing `isprime(n)` in the MATLAB command window, where `n` is the input number you want to check for primality.

User Sandeep Sherpur
by
8.2k points