Filter löschen
Filter löschen

Info

Diese Frage ist geschlossen. Öffnen Sie sie erneut, um sie zu bearbeiten oder zu beantworten.

Cleaner way to write a series of similar sequences

1 Ansicht (letzte 30 Tage)
Jasmine Karim
Jasmine Karim am 27 Aug. 2018
Geschlossen: MATLAB Answer Bot am 20 Aug. 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 Kommentar
Stephen23
Stephen23 am 28 Aug. 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:

Antworten (1)

OCDER
OCDER am 27 Aug. 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

Diese Frage ist geschlossen.

Community Treasure Hunt

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

Start Hunting!

Translated by