Info

此问题已关闭。 请重新打开它进行编辑或回答。

Cleaner way to write a series of similar sequences

1 次查看(过去 30 天)
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 个评论
Stephen23
Stephen23 2018-8-28
"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:

回答(1 个)

OCDER
OCDER 2018-8-27
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

此问题已关闭。

Community Treasure Hunt

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

Start Hunting!

Translated by