How to remove an element based on a condition

27 views (last 30 days)
Hey guys,
So, I need to write the code for finding prime numbers and I'm trying to do so by removing the elements which can be perfectly divided. In order to remove the elements, I'm using the instructions given here:
Instead of a simply mean condition as above, I'm using the remainder function and a loop as follows:
r=1:20;
n=length(r)
for i=2:1:n/2
r(rem(r,i)=0)=[];
end
disp(r)
Right now, I'm just doing a test for an array from 1:20. The loop for i cycles through all the possible values and as soon as it finds an element that can be perfectly divided by any i, I want the element to be removed from the array. But, I'm getting the following error:
subscript indices must be either positive integers less than 2^31
or logicals
error: called from
prime5 at line 4 column 14
Can someone please explain the error and how I can circumvent it? Thanks.

Answers (1)

Image Analyst
Image Analyst on 27 Jun 2016
You need to use == instead of =. And since r shrinks as you move along deleting elements, you must start at the end and work toward the front:
r = 1:20;
n = length(r)
for i = n/2 : -1 : 2
r(rem(r, i) == 0) = [];
end
disp(r)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!