How to repeat function for different arrays?

2 vues (au cours des 30 derniers jours)
Redmond Riddell
Redmond Riddell le 3 Juin 2018
Modifié(e) : Stephen23 le 4 Juin 2018
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 commentaire
Stephen23
Stephen23 le 4 Juin 2018
Modifié(e) : Stephen23 le 4 Juin 2018
"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!

Connectez-vous pour commenter.

Réponses (2)

dpb
dpb le 3 Juin 2018
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 commentaire
Redmond Riddell
Redmond Riddell le 3 Juin 2018
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!

Connectez-vous pour commenter.


Jeff Miller
Jeff Miller le 4 Juin 2018
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

Catégories

En savoir plus sur Performance and Memory 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