How to repeat function for different arrays?

1 回表示 (過去 30 日間)
Redmond Riddell
Redmond Riddell 2018 年 6 月 3 日
編集済み: Stephen23 2018 年 6 月 4 日
Hi there, I am trying to repeat a function for multiple arrays, such as this:
L_it(A_it < 0) = L_it(1);
I_it(A_it < 0) = I_it(1);
Y_it(A_it < 0) = Y_it(1);
or
Y_t(t)=sum(Y_it(:,t));
K_t(t)=sum(K_it(:,t));
dL_t(t)=sum(dL_it(:,t));
is there an easy way to do this or should I just repeat the function about 50 times for each array?
Thank you very much!
  1 件のコメント
Stephen23
Stephen23 2018 年 6 月 4 日
編集済み: Stephen23 2018 年 6 月 4 日
"is there an easy way to do this..."
No, there is no easy way to do this. There are slow, complex, buggy ways of doing this, that all experienced MATLAB users will tell you to avoid. Read this to know why:
"...or should I just repeat the function about 50 times for each array?"
You should not do that either. Copy-and-pasting code is a sign that you should be using a loop. Loops are trivial to use with highly efficient and easy-to-debug indexing. Ergo, put your data into one array and use indexing. Or use a table and one of its many supporting functions, e.g. varfun.
It may be that once your data is all in one array that you don't even need to use a loop: read this to know why:
Remember that computers are really just based around doing simple numeric tasks quickly in a loop. So when you sit and copy-and-paste code you are just doing the computer's job for it: defining a loop (explicitly or implicitly (e.g. vectorized code)) tells the computer to do its job!

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

回答 (2 件)

dpb
dpb 2018 年 6 月 3 日
If there are related variables which need similar operations, then don't create them as individually-named variables but as members of a more abstract data construct.
One way would be to use a table and then one can use varfun or simply address variables wanted.
  1 件のコメント
Redmond Riddell
Redmond Riddell 2018 年 6 月 3 日
Hmm, is there any way to keep the data in the same table? I am still at a loss how to perform the given function using varfun!

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


Jeff Miller
Jeff Miller 2018 年 6 月 4 日
Just to give a slight variant of db's answer, another option is to hold all these arrays as fields within a structure, say 's'. So, instead of initializing your arrays L_it, I_it, etc, initialize each one as a field within the structure:
s.L_it = % initialization of L
s.I_it = % initialization of I
% and so on
Now, you can get a list of all of s's fields (i.e., a list of your different arrays) and iterate over them with something like this:
fields = fieldnames(s);
for iField=1:numel(fields)
onearray = s.(fields{iField});
% Compute what you want from each array
end

カテゴリ

Help Center および File ExchangePerformance and Memory についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by