Hello there
I'm attempting to use the prod function to construct the factorial code more quickly, but I'm encountering a problem.
Please let me know the reason for this and what I might be doing incorrectly.
Many thanks
n = fi(1); % n max is 20
n =
1 DataTypeMode: Fixed-point: binary point scaling Signedness: Signed WordLength: 16 FractionLength: 14
indx = max(1,max(min(n,20)));
for g = 1:indx
out(:) = prod(1:indx,'all');
end
Error using prod
Invalid data type. First argument must be numeric or logical.

 採用された回答

Chunru
Chunru 2022 年 9 月 2 日
編集済み: Chunru 2022 年 9 月 2 日

0 投票

n = 5 % n max is 20
n = 5
out = cumprod(1:n)
out = 1×5
1 2 6 24 120
n = fi(5); % n max is 20
out = (1:n);
for i = 2:n
out(i) = out(i-1)*i;
end
out
out =
1 2 6 24 120 DataTypeMode: Fixed-point: binary point scaling Signedness: Signed WordLength: 16 FractionLength: 0

6 件のコメント

Life is Wonderful
Life is Wonderful 2022 年 9 月 2 日
How ?
Error is due to "Invalid data type" and not in due to prod.
Chunru
Chunru 2022 年 9 月 2 日
You use "fi", or fixed point format. The prod function does not support the data type.
In above, I use double type for all data.
Life is Wonderful
Life is Wonderful 2022 年 9 月 2 日
You see Error,
n = fi(1); % n max is 20
indx = max(1,max(min(n,20)));
for g = 1:indx
out(:) = cumprod(1:indx);
end
Error using cumprod
Invalid data type. First input argument must be numeric or logical.
Life is Wonderful
Life is Wonderful 2022 年 9 月 2 日
Yes, I did specify that the code I'm using is fixed point rather than double.
Do you have another suggestion?
Chunru
Chunru 2022 年 9 月 2 日
See above for the fi data type.
Life is Wonderful
Life is Wonderful 2022 年 9 月 5 日
Thanks a lot,

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File Exchange で Subsystems についてさらに検索

製品

リリース

R2022a

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by