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

1 view (last 30 days)
Kenichi on 11 Sep 2022
Commented: Kenichi on 11 Sep 2022
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 CommentsShowHide 1 older comment
Kenichi on 11 Sep 2022
Thank you!

Jan on 11 Sep 2022
Edited: Jan on 11 Sep 2022
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)
Kenichi on 11 Sep 2022

### Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

R2022a

### Community Treasure Hunt

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

Start Hunting!

Translated by