Better ways to achieve maintainable code involving n-d arrays?

1 次查看(过去 30 天)
Dear All,
I have a question on the best way to write maintainable and readable code inolving n-d arrays.
To explain my problem, look at the following code snippet involving "someArray" which is a m-by-ntime matrix,
the second dimension is time say.
I initialise the array and then step forward in time using an evolution equation:
someArray (:,1) = intialisation(someValues);
for tstep = 2:ntime
someArray (:,tstep) = evolution_equation( someArray (:,tstep - 1), other_stuff );
end
This innocent piece of code is a maintenance nightmare: Imagine in a next revision someArray would have a
different dimension say m-by-ntime-by-k-by-j. Even if the logic of the calculation does not change a bit I have
to modify every expression involving someArray for purely syntactical reasons:
someArray (:,1,:,:) = intialisation(someValues);
for tstep = 2:ntime
someArray (:,tstep,:,:) = evolution_equation( someArray (:,tstep - 1,:,:), other_stuff );
end
Needless to say I have plenty of "someArrays" and many lines of code like this and I get sick and tired of
doing those "mindless" modifications.
So my question is simply:
  • Do you encounter this problem as well?
  • Do you know of a better (= more maintenance friendly) way of doing this?
Thank you gg

回答(1 个)

Oleg Komarov
Oleg Komarov 2011-3-2
You may find useful the comma-separated list expansion:
clear B
tstep = 1;
dims = [2,2,2,2];
A = rand(dims);
% Comma-Separated List
csl = cellstr(repmat(':',ndims(A)-2,1));
% Dynamic assignment with csl expansion
B(:,tstep,csl{:}) = sum(A,2);
Try to change the value of dims to see what happens.
Oleg
  2 个评论
Jan
Jan 2011-3-2
Typo: "csle"->"csl". I'd prefer this to create the cell string: csl = cell(1, ndims(A)-2); csl(:)={':'};
But for the small number of expected dimensions the absolute speed difference is negligible.
gg
gg 2011-12-14
hmm, if you always append to the right this might work. But I consider this more a partial workaround than a solution.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Statistics and Machine Learning Toolbox 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by