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

1 回表示 (過去 30 日間)
gg
gg 2011 年 3 月 2 日
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 Center および File ExchangeMatrices and Arrays についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by