MATLAB: How to create a list where it shows the values from the list 1:N so that in the list it says which numbers are prime alternatefprintfprime Question answered Best Answer Try this:N = 55;primeNumbers = primes(N)fprintf('list: ');for k = 1 : N fprintf('%d', k); if ismember(k, primeNumbers) fprintf(' (prime), '); else fprintf(', '); endendYou get in the command window:list: 1, 2 (prime), 3 (prime), 4, 5 (prime), 6, 7 (prime), 8, 9, 10, 11 (prime), 12, 13 (prime), 14, 15, 16, 17 (prime), 18, 19 (prime), 20, 21, 22, 23 (prime), 24, 25, 26, 27, 28, 29 (prime), 30, 31 (prime), 32, 33, 34, 35, 36, 37 (prime), 38, 39, 40, 41 (prime), 42, 43 (prime), 44, 45, 46, 47 (prime), 48, 49, 50, 51, 52, 53 (prime), 54, 55, How's that? If you need to not print the final trailing comma, you can print a backspace. Related SolutionsMATLAB: How to replace the last value in the output string to ‘and *value*.’ instead of ‘, *value*,’ Tryfor i = 1 : N fprintf('%d', i); if ismember(i, result) fprintf(' (prime)'); end if i < N fprintf(', '); else fprintf('.\n'); endend MATLAB: Prime number list checker Your code for resetting "counter" is inside an if-test. You need to move it so that it always executes. E.g.,%#Want to test numbers 2:n if they're primeprompt = input('max number to test: ');n = prompt;l = 2; %#start of mod testcounter = 0;ticfor i = 2:n %#cycle to test 2 up to n t = floor(sqrt(i)); %#Only need to test up to root of number counter = 0; % <-- Moved from below for l = 2:t if mod(i,l) == 0 break else counter = (counter + 1); end end if counter == t-1 %# if tested up to the root of the number, it must be prime prime = sprintf('%d is prime', round(i)); disp(prime)% counter = 0; % <-- Moved to up above endendtoc Related QuestionList functions on fprintfList(Vecor) GenerationSet list boxList box itemsTrying to display a list of numbersCreating a list from another list
Best Answer