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 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