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

1 次查看(过去 30 天)
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

请先登录,再进行评论。

采纳的回答

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 CenterFile Exchange 中查找有关 Startup and Shutdown 的更多信息

标签

产品


版本

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by