How to pull out numbers from a vector in matlab?

5 views (last 30 days)
I am having trouble figuring out how to extract certain points out of the vector I create.  The point of this problem is to create a function that finds the first nth prime numbers without using native matlab functions.  I create a large matrix that I narrow down to create one that has a large number of prime numbers.  Then out of that function I pull out the first n prime numbers.  I keep getting an error that says "Index exceeds matrix dimensions.".  Any help would be great. The function is below:
function [ prime ] = HW01_problem_07( n )
%UNTITLED Summary of this function goes here
%   Detailed explanation goes here
N=10*n;
array = 2:N;
prime=[];
for i = 1:length(array)
    if array(i) ~= 0 
        for j = i+2: length(array) 
            if mod(array(j), array(i)) == 0 
            array(j) = 0; 
            end 
        end 
    end 
        if array(i) ~= 0 
          prime(length(prime) + 1) = array(i);
          prime=prime(1:n);
          
        end
        
end

Answers (1)

Walter Roberson
Walter Roberson on 10 Feb 2016
prime=prime(1:n);
needs to go after the "for" loop.

Community Treasure Hunt

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

Start Hunting!