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

1 visualización (últimos 30 días)
gg
gg el 2 de Mzo. de 2011
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

Respuestas (1)

Oleg Komarov
Oleg Komarov el 2 de Mzo. de 2011
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 comentarios
Jan
Jan el 2 de Mzo. de 2011
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 el 14 de Dic. de 2011
hmm, if you always append to the right this might work. But I consider this more a partial workaround than a solution.

Iniciar sesión para comentar.

Categorías

Más información sobre Statistics and Machine Learning Toolbox en Help Center y File Exchange.

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by