How to loop through the same operation on multiple variables

조회 수: 20 (최근 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 CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by