Why doesn't the for loop work?
1 view (last 30 days)
I want to keep only the prime numbers in vector and to replace the others with 0s. It seems so simple yet it's not working, what's to be done? :(
Vilém Frynta on 6 Jan 2023
Edited: Vilém Frynta on 6 Jan 2023
x(p==0)=0; % Put zeros on the positions where p == 0 in vector X
Is this what you wanted?
This way you do not even need for loop, which is generally better.
However, if you intend to use the for loop, this is the possible way:
z = x; % create new variable, so you do not overwrite the original one
I'm sure there are other ways to do this as well. Hope I helped.
More Answers (1)
Bora Eryilmaz on 6 Jan 2023
Edited: Bora Eryilmaz on 6 Jan 2023
p = isprime(p) gives you a logical vector, similar to
p = [true true false true]
When you try to assign i to p(i) it converts the value of i to a logical value; it does not assign i to p(i). See for example
p(3) = 3
p(3) did not become 3, it became the logical equivalent of 3, which is true, a.k.a. 1.
Instead you can do as simple assignment of 0 to elements of x that are not prime numbers:
x = 1:16;
p = isprime(x);
x(~p) = 0