Creating a Factorial for an Input/Output Array using Loops
3 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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!
1 Kommentar
Antworten (1)
Voss
am 24 Dez. 2021
Bearbeitet: Voss
am 24 Dez. 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]);
0 Kommentare
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!