How to select last digit of numbers and put it into a matrix?

조회 수: 19 (최근 30일)
Francisco Boudagh
Francisco Boudagh 2021년 4월 26일
답변: John D'Errico 2021년 4월 26일
I just want to start with the fact that this is not a school assignment, I do this privately for the sake of interest.
Here is my code:
% prime number pattern test
close all;
clc;
clear all;
num = 1:6000;
idx = isprime(num);
A = num(idx);
if length(A) > 100; A = A(1:100); end
A = reshape(A, 10, 10);
imagesc(A)
colorbar
axis equal tight;
-----------------------------------------------------------------
So, my matrix A is contains first 100 prime numbers. I want matrix A to contain only the last digits of the first 100 prime numbers. That is, 1,3,7,9.
How do I do this?
Thanks for any help, everything is appreciated
  댓글 수: 1
Walter Roberson
Walter Roberson 2021년 4월 26일
num = 1:600;
idx = isprime(num);
A = num(idx);
if length(A) > 100; A = A(1:100); end
A = reshape(A, 10, 10);
A = mod(A,10);
imagesc(A)
colorbar
axis equal tight;

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

채택된 답변

John D'Errico
John D'Errico 2021년 4월 26일
Well, since you did write a fair amount of code, homework or not is irrelevant. There are some issues with your code however.
First, it seems silly to test numbers for primality using isprime as you did. If you intend to do that, then just use primes(6000) in the first place to generate the list of primes.
Next, this is silly
if length(A) > 100; A = A(1:100); end
A = reshape(A, 10, 10);
Think about it. What will you do if length(A) is LESS than 100? Your code will fail anyway, since the reshape will fail. Therefore, you might as well replace the above code with
A = reshape(A(1:100),10,10);
Better yet, if you have the symbolic toolbox which provides the function nthprime, you could simplify your code nicely. Note my use of mod to generate the last digit. As well, see that you can specify the size of the final array.
primearraysize = [10,10];
A = primes(nthprime(prod(primearraysize)));
A = reshape(A,primearraysize);
lastdigit = mod(A,10);
imagesc(lastdigit)
colorbar
axis equal tight;

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Number Theory에 대해 자세히 알아보기

제품


릴리스

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by