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

2 vues (au cours des 30 derniers jours)
Kenichi
Kenichi le 11 Sep 2022
Commenté : Kenichi le 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 commentaires
Stephen23
Stephen23 le 11 Sep 2022
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 le 11 Sep 2022
Thank you!

Connectez-vous pour commenter.

Réponse acceptée

Jan
Jan le 11 Sep 2022
Modifié(e) : Jan le 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)

Plus de réponses (0)

Catégories

En savoir plus sur Startup and Shutdown dans Help Center et File Exchange

Produits


Version

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by