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

13 次查看(过去 30 天)
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