multidimensional colon operator?

I want to do something like that below: copy an N-dimensional array into a N+1-dimensional array at index t in the last dimension. Can this be done efficiently and cleaner than umpteen if-tests or nasty permutes?
function A = insert_x_into_A(A,x,t)
if ndims(A) == 2
A(:,t) = x;
elseif ndims(A) == 3
A(:,:,t) = x;
elseif ndims(A) == 4
A(:,:,:,t) = x;
...
end
I think that something like the pseudo-code below would be neat
function A = insert_x_into_A(A,x,t)
A(colon(ndims(x)),t) = x;

 채택된 답변

Jan
Jan 2011년 2월 4일

5 개 추천

Two approaches: 1. Reshape the matrix at first:
function A = insert_x_into_A(A,x,t)
siz = size(A);
A = reshape(A, [], siz(end));
A(:, t) = x(:);
A = reshape(A, siz);
2. Use a cell as index vector: EDITED: Cleaned up with Bruno's suggestion.
function A = insert_x_into_A(A,x,t)
idx(1:ndims(A) - 1) = {':'};
A(idx{:},t) = x;

댓글 수: 4

Kenneth Eaton
Kenneth Eaton 2011년 2월 4일
I vote for the second one. It's often overlooked that you can index a matrix with the character ':'.
Bruno Luong
Bruno Luong 2011년 2월 4일
Just simplify few lines of Jan's code:
function A = insert_x_into_A(A,x,t)
idx(1:ndims(A)-1) = {':'};
A(idx{:},t) = x;
Jan
Jan 2011년 2월 4일
@Bruno: Nicer. I'll insert it in my approach.
Knut
Knut 2013년 5월 7일
편집: Knut 2013년 5월 7일
Is this documented anywhere? Am I supposed to be able to do stuff like:
ord = 3;
buffN = zeros(5*ones(1,ord));
shiftidx1(1:ord) = {'2:end'};
shiftidx2(1:ord) = {'1:(end-1)'};
buffN(shiftidx1{:}) = buffN(shiftidx2{:});
(circshift seems to be made for this purpose, but it seems slow for my purpose)

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Matt Fig
Matt Fig 2011년 2월 4일

0 개 추천

If you want to get real evil:
function A = insert_x_into_A(A,x,t)
col = repmat(':,',1,ndims(A)-1);
eval(['A(',col,'t) = x;'])
Though I don't know why you would need such a specific function.

댓글 수: 2

Jan
Jan 2011년 2월 4일
Matt, I can see your EVAL!
Matt Fig
Matt Fig 2011년 2월 4일
I couldn't resist. This seems like a safe application anyway.

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Matrix Indexing에 대해 자세히 알아보기

질문:

2011년 2월 4일

Community Treasure Hunt

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

Start Hunting!

Translated by