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
댓글 수: 0
답변 (1개)
Oleg Komarov
2011년 3월 2일
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
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.
참고 항목
카테고리
Help Center 및 File 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!