Creating a Factorial for an Input/Output Array using Loops

3 vues (au cours des 30 derniers jours)
Bethany Roberts
Bethany Roberts le 30 Mar 2021
Modifié(e) : Voss le 24 Déc 2021
I was tasked a homework problem to take a user-inputted array and output the resulting factorial of each array element in a new array. We're only allowed to use the following built-in functions: length, size, round, abs, fprintf, plot. (In my code below I'm using disp as a easy way to quickly see the output, I'll be changing it to fprintf later.)
I don't have issues creating a factorial loop for a single number, but I'm unsure how to take an array, "factorialize" it, and output it in another array. Here's my code thus far:
Array = input('Enter an array of positive integers in brackets: ');
N = length(Array);
for k = 1:N
if Array(k)<0 || (round(Array(k)) ~= Array(k))
error('Array can''t have negative or fractional numbers.\nArray A(%g) = %g', k, Array(k));
else
f(1) = [Array(k)*k];
k = k+1;
end
end
disp([f]);
The portion for checking the if statement works correctly, it prints the error whenever a fraction or negative number is input.
My problem is actually "factorializing" the array under the else statement. I've tried a few different combos of placeholders to create the output array, but I can't seem to figure out the right way to do it for it to result in actually printing an array and not a single integer.
Thanks in advance for the help!

Réponses (1)

Voss
Voss le 24 Déc 2021
Modifié(e) : Voss le 24 Déc 2021
% Array = input('Enter an array of positive integers in brackets: ');
Array = [4 7 2 0 3 1]; % can't take input here, so suppose they entered this Array
N = length(Array);
for k = 1:N
if Array(k)<0 || (round(Array(k)) ~= Array(k))
error('Array can''t have negative or fractional numbers.\nArray A(%g) = %g', k, Array(k));
else
f(k) = 1;
for m = 1:Array(k)
f(k) = m*f(k);
end
end
end
disp([f]);
24 5040 2 1 6 1

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Produits


Version

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by