フィルターのクリア

What is wrong with for loop iteration that is put in a function?

1 回表示 (過去 30 日間)
Kenichi
Kenichi 2022 年 9 月 11 日
コメント済み: Kenichi 2022 年 9 月 11 日
Hi! I'm wondering on this code I made:
a = input('Please insert a: ')
b = input('Please insert b: ')
arr = []
for i = a:b-1
for j = a+1:b
if and(composite(i), composite(j), composite(i+j))
arr = [arr; i j]
end
end
end
arr
and I got this error message:
Output argument "bool" (and possibly others) not assigned a value in the
execution with "composite" function.
Error in untitled10 (line 6)
if and(composite(i), composite(j), composite(i+j))
I did make a composite function:
that run perfectly but when I put iteration numbers in it, it gives the error message before
function bool = composite(n)
for i = 2:n
for j = 2:n
if i*j == n
bool = true;
end
end
end
if n ==2
bool = false;
elseif n ==1
bool = false;
end
end
Thank you!
  2 件のコメント
Stephen23
Stephen23 2022 年 9 月 11 日
There are lots of values of n for which the output is not defined: 0, 3, 5, 7, ...
b = composite(7)
Output argument "bool" (and possibly others) not assigned a value in the execution with "solution>composite" function.
function bool = composite(n)
for i = 2:n
for j = 2:n
if i*j == n
bool = true;
end
end
end
if n ==2
bool = false;
elseif n ==1
bool = false;
end
end
Kenichi
Kenichi 2022 年 9 月 11 日
Thank you!

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

採用された回答

Jan
Jan 2022 年 9 月 11 日
編集済み: Jan 2022 年 9 月 11 日
function bool = composite(n)
bool = false; % Create a default value
if n > 2
for i = 2:n
for j = 2:n
if i*j == n
bool = true;
return; % No need for further tests
end
end
end
end
end
Your function composite() computes the same as the much faster Matlab function isprime() except for the input 2. The function composite can be improved: if e.g. i*j > n, the inner loop can be stopped by a break.
This command will fail at next, because Matlab's and() accept 2 inputs only.
if and(composite(i), composite(j), composite(i+j))
Maybe you mean
if composite(i) && composite(j) && composite(i+j)

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeStartup and Shutdown についてさらに検索

タグ

製品


リリース

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by