Borrar filtros
Borrar filtros

Info

La pregunta está cerrada. Vuélvala a abrir para editarla o responderla.

Cleaner way to write a series of similar sequences

1 visualización (últimos 30 días)
Jasmine Karim
Jasmine Karim el 27 de Ag. de 2018
Cerrada: MATLAB Answer Bot el 20 de Ag. de 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 comentario
Stephen23
Stephen23 el 28 de Ag. de 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:

Respuestas (1)

OCDER
OCDER el 27 de Ag. de 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

La pregunta está cerrada.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by