Changing prime numbers in a matrix

조회 수: 1 (최근 30일)
Doga Ince
Doga Ince 2021년 6월 16일
댓글: Scott MacKenzie 2021년 6월 16일
I printed a 100x100 random matrix of integers from 1 to 50. However, I want to replace the prime numbers in this matrix with the number 1415. How can I replace the prime numbers in that matrix with a specific number (1415)? Thank you.

답변 (1개)

Scott MacKenzie
Scott MacKenzie 2021년 6월 16일
M = randi([1 50],100);
M(isprime(M)) = 1415;
  댓글 수: 2
Doga Ince
Doga Ince 2021년 6월 16일
Thank you but i am getting error 😥
Could I be getting an error because I want to both find the prime numbers in my matrix and replace those numbers with 1415? Can you help me?
Scott MacKenzie
Scott MacKenzie 2021년 6월 16일
Ok, sure. This modification stores the locations of the prime numbers in a logical variable, outputs the prime numbers, then replaces the prime numbers in M with 1415.
M = randi([1 50],100);
% find locations in M containing prime number
primeLogical = isprime(M);
% output prime numbers in M
M(primeLogical)
% change prime numbers in M to 1415
M(primeLogical) = 1415;

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

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by