Creating a Factorial for an Input/Output Array using Loops

조회 수: 3 (최근 30일)
Bethany Roberts
Bethany Roberts 2021년 3월 30일
편집: Voss 2021년 12월 24일
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개)

Voss
Voss 2021년 12월 24일
편집: Voss 2021년 12월 24일
% 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

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품


릴리스

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by