find prime numbers without isprime() or primes() in matlab

To find prime numbers in MATLAB without using the built-in functions isprime or primes, we can use a simple algorithm that involves checking every number in a given range to see if it's a prime number. Here's one way to do it:

main.m
% Define the range of numbers to check
n = 100;

% Initialize an empty vector to store the prime numbers
primes = [];

% Loop over every number in the range
for num = 2:n
    % Assume the number is prime unless proven otherwise
    isprime = true;

    % Check if the number is divisible by any integer from 2 to num - 1
    for divisor = 2:num-1
        if mod(num, divisor) == 0
            % If the number is divisible, it's not a prime number
            isprime = false;
            break;
        end
    end
    
    % If the number is prime, add it to the list of primes
    if isprime
        primes(end+1) = num;
    end
end

% Display the list of prime numbers
disp(primes)
685 chars
29 lines

This code uses a nested for loop to check whether each number in the range is a prime number. The outer loop runs from 2 to n, and the inner loop checks whether each number is divisible by any integer from 2 to the number itself minus 1. If the number is divisible by any integer, it's not a prime number, and the loop breaks to move on to the next number. If the number is not divisible by any integer, it's a prime number and is added to the list of primes. Finally, the list of prime numbers is displayed in the command window.

gistlibby LogSnag