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

25 views (last 30 days)
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 Comment
Walter Roberson
Walter Roberson on 26 Apr 2021
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;

Sign in to comment.

Accepted Answer

John D'Errico
John D'Errico on 26 Apr 2021
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;

More Answers (0)

Products


Release

R2019b

Community Treasure Hunt

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

Start Hunting!