How to loop through the same operation on multiple variables
13 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Apologies up front, I'm sure this is a question asked before but I couldn't seem to find the right search terms get the answer. I want to perform the same operation on multiple variables, after checking that each variable meets a certain criteria. So I have:
function Result = myFun(Var1,Var2,Var3)
if meetsCriteria(Var1)
Var1 = operation(Var1);
end
if meetsCriteria(Var2)
Var2 = operation(Var2);
end
if meetsCriteria(Var3)
Var3 = operation(Var3);
end
Result = otherOperation(Var1,Var2,Var3)
Is there a way to shorten this into a loop?
1 comentario
Stephen23
el 27 de Nov. de 2019
Editada: Stephen23
el 27 de Nov. de 2019
"How to loop through the same operation on multiple variables?"
"I'm sure this is a question asked before..."
Yes, many times.
"I want to perform the same operation on multiple variables..."
Writing code that accesses variables dynamically is one way that beginners force themselves into writing slow, complex, obfuscated, buggy code that is hard to debug. Read this to know more:
You should use indexing. Indexing is neat, simple, easy to debug, and very efficient (unlike what you are trying to do).
Respuestas (1)
Stephen23
el 27 de Nov. de 2019
Editada: Stephen23
el 27 de Nov. de 2019
"Is there a way to shorten this into a loop?"
By far the simplest and most efficient solution is to use a cell array and indexing:
In practice this means instead of using numbered variables (which are invariably an indication that you are doing something wrong) you would store those arrays in one cell array:
function Result = myFun(Var1,Var2,Var3)
C = {Var1,Var2,Var3};
for k = 1:numel(C)
if meetsCriteria(C{k})
C{k} = operation(C{k});
end
end
Result = otherOperation(C{:});
end
Read these to know what C{:} does:
function Result = myFun(varargin)
for k = 1:numel(varargin)
if meetsCriteria(varargin{k})
varargin{k} = operation(varargin{k});
end
end
Result = otherOperation(C{:});
end
0 comentarios
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!