How to loop through the same operation on multiple variables

87 vues (au cours des 30 derniers jours)
Jonathan Martin
Jonathan Martin le 27 Nov 2019
Modifié(e) : Stephen23 le 27 Nov 2019
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 commentaire
Stephen23
Stephen23 le 27 Nov 2019
Modifié(e) : Stephen23 le 27 Nov 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).

Connectez-vous pour commenter.

Réponses (1)

Stephen23
Stephen23 le 27 Nov 2019
Modifié(e) : Stephen23 le 27 Nov 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:
You could even define the function with varargin to avoid the superfluous intermediate variables:
function Result = myFun(varargin)
for k = 1:numel(varargin)
if meetsCriteria(varargin{k})
varargin{k} = operation(varargin{k});
end
end
Result = otherOperation(C{:});
end

Catégories

En savoir plus sur Function Creation dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by