How to code NESTED CYCLES
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
pipor
el 9 de Sept. de 2023
Comentada: Image Analyst
el 10 de Sept. de 2023
f=[3 6 3 9]
b=[5 8 10 12]
a is a function with parameter f and b!
for l=1:numel(b)
for i=1:numel(f)
a(f(i),b(l))
end
end
but this is a problem:
if b is empty the function won't loop me with "f"
1 comentario
Respuesta aceptada
Star Strider
el 9 de Sept. de 2023
I would set the empty array to 1 (so that it iterates one time only) and be done with it —
a = @(x,y) [x y];
f = [3 6 3 9]; % Neither Empty
b = [5 8 10 12];
if isempty(f)
f = NaN;
elseif isempty(b)
b = NaN;
end
for l=1:numel(b)
for i=1:numel(f)
q = a(f(i),b(l))
end
end
f = []; % 'f' Empty
b = [5 8 10 12];
if isempty(f)
f = NaN;
elseif isempty(b)
b = NaN;
end
for l=1:numel(b)
for i=1:numel(f)
q = a(f(i),b(l))
end
end
f = [3 6 3 9]; % 'b' Empty
b = [];
if isempty(f)
f = NaN;
elseif isempty(b)
b = NaN;
end
for l=1:numel(b)
for i=1:numel(f)
q = a(f(i),b(l))
end
end
The ‘default’ value (here ‘NaN’) can be any value that makes sense in the context of whatever ‘a’ does. If a given argument is added, then set it to the identity element for that operation, so if it is added set it to 0 if the associated vector is empty, if it is multiplied, set it to 1.
.
0 comentarios
Más respuestas (2)
Bruno Luong
el 9 de Sept. de 2023
Reverse the 2 loops, then it loops on f
f=[3 6 3 9]
b=[]
for i=1:numel(f)
f(i)
for l=1:numel(b)
a(f(i),b(l))
end
end
2 comentarios
Bruno Luong
el 9 de Sept. de 2023
Editada: Bruno Luong
el 9 de Sept. de 2023
Split in three loops if you have to
for i=1:numel(f)
for l=1:numel(b)
% ... do something with both f(i) and b(l)
a(f(i),b(l))
end
end
for i=1:numel(f)
% ... do something with f(i) ALONE
end
for l=1:numel(b)
% ... do something with b(l) ALONE
end
Image Analyst
el 9 de Sept. de 2023
Check them in advance:
if isempty(b)
% What to do
return;
end
if isempty(f)
% What to do
return;
end
for l=1:numel(b)
for i=1:numel(f)
something = a(f(i),b(l))
end
end
2 comentarios
Image Analyst
el 10 de Sept. de 2023
Correct. Why would you want to continue if one is empty? If you do you'll just get an error. If you can "fix" the situation, do so inside the if -- for example Star set them to nan instead. If you can't fix the situation, you should just exit the code after alerting the user.
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!