What is wrong with for loop iteration that is put in a function?
1 visualizzazione (ultimi 30 giorni)
Mostra commenti meno recenti
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 Commenti
Stephen23
il 11 Set 2022
There are lots of values of n for which the output is not defined: 0, 3, 5, 7, ...
b = composite(7)
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
Risposta accettata
Jan
il 11 Set 2022
Modificato: Jan
il 11 Set 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)
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Startup and Shutdown in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!