Why doesn't the for loop work?

조회 수: 1 (최근 30일)
Emilia
Emilia 2023년 1월 6일
댓글: Vilém Frynta 2023년 1월 6일
x=1:16;
p=isprime(x);
for i=1:16
if p(i)==1
p(i)=i;
end
end
A=reshape(p,4,4);
A=A';
display(A);
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
Vilém Frynta 2023년 1월 6일
편집: Vilém Frynta 2023년 1월 6일
x=1:16;
p=isprime(x);
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:
x=1:16;
p=isprime(x);
z = x; % create new variable, so you do not overwrite the original one
for i=1:16
if p(i)==1
z(i)=i;
else
z(i)=0;
end
end
z
z = 1×16
0 2 3 0 5 0 7 0 0 0 11 0 13 0 0 0
I'm sure there are other ways to do this as well. Hope I helped.
  댓글 수: 3
Bora Eryilmaz
Bora Eryilmaz 2023년 1월 6일
Since p is already a logical vector, p==0 is unnecessary. x(~p) would be a bit simpler.
Vilém Frynta
Vilém Frynta 2023년 1월 6일
Yes, I thought that would be possible, thanks for additional information ÷)

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Bora Eryilmaz
Bora Eryilmaz 2023년 1월 6일
편집: Bora Eryilmaz 2023년 1월 6일
p = isprime(p) gives you a logical vector, similar to
p = [true true false true]
p = 1×4 logical array
1 1 0 1
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 = 1×4 logical array
1 1 1 1
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
x = 1×16
0 2 3 0 5 0 7 0 0 0 11 0 13 0 0 0
  댓글 수: 1
Emilia
Emilia 2023년 1월 6일
It's all clear now, thank you!!!

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by