How to loop through the same operation on multiple variables

19 ビュー (過去 30 日間)
Jonathan Martin
Jonathan Martin 2019 年 11 月 27 日
編集済み: Stephen23 2019 年 11 月 27 日
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 件のコメント
Stephen23
Stephen23 2019 年 11 月 27 日
編集済み: Stephen23 2019 年 11 月 27 日
"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).

サインインしてコメントする。

回答 (1 件)

Stephen23
Stephen23 2019 年 11 月 27 日
編集済み: Stephen23 2019 年 11 月 27 日
"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

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by