Azzera filtri
Azzera filtri

Info

Questa domanda è chiusa. Riaprila per modificarla o per rispondere.

Cleaner way to write a series of similar sequences

1 visualizzazione (ultimi 30 giorni)
Jasmine Karim
Jasmine Karim il 27 Ago 2018
Chiuso: MATLAB Answer Bot il 20 Ago 2021
Hi, I'm wondering if there is, in general, a cleaner way to write a series of repeating sequences, but that pull from different arrays. For example, I currently have the following:
A{x,y} = (sampleE(x,y)/sampleW(x,y))*100;
B{x,y} = (sampleF(x,y)/sampleW(x,y))*100;
C{x,y} = (sampleG(x,y)/sampleZ(x,y))*100;
D{x,y} = (sampleH(x,y)/sampleZ(x,y))*100;
All of the variables (sampleE, sampleW, etc.) are held in different arrays. Just curious if there is a neater way to write this than having them repeat.
  1 Commento
Stephen23
Stephen23 il 28 Ago 2018
"All of the variables (sampleE, sampleW, etc.) are held in different arrays. Just curious if there is a neater way to write this than having them repeat."
Yes, there is a neat way: simply put your data into one array and use indexing! Indexing is neat, simple, very efficient, and easy to debug.
In contrast what you are trying to do, which involves dynamically accessing variable names, is one way that beginners force themselves into writing slow, complex, buggy code that is hard to debug. Read this to know more:

Risposte (1)

OCDER
OCDER il 27 Ago 2018
Nope, that style of coding is going to end up with repeated codes like the one you have shown. This should be a good read for you:
Essentially, naming variables like Var1, Var2, Var3, A, B, C, D, etc should be avoided. Use cell arrays or structures so that you can use the power of arrayfun, cellfun, for loops, while loops, and parfor loops.
Example:
Instead of Var1, Var2, etc, use Var{1}, Var{2}, ...
for j = 1:length(Var)
Var{j} = j + 1 + ...;
end

Questa domanda è chiusa.

Community Treasure Hunt

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

Start Hunting!

Translated by