How to pull out numbers from a vector in matlab?

5 ビュー (過去 30 日間)
Roosky Jones
Roosky Jones 2016 年 2 月 10 日
回答済み: Walter Roberson 2016 年 2 月 10 日
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

回答 (1 件)

Walter Roberson
Walter Roberson 2016 年 2 月 10 日
prime=prime(1:n);
needs to go after the "for" loop.

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by