필터 지우기
필터 지우기

Append matrix to another matrix in Matlab

조회 수: 17 (최근 30일)
Alex
Alex 2015년 3월 20일
편집: James Tursa 2015년 3월 20일
I have a matrix M=[4 3 2 1;1 2 3 4]. I want to append different size matrices at each iteration:
M=[4 3 2 1;1 2 3 4];
for i=1:t
newM=createNewMatrix;
M=[M;newM];
end
newM can be [] or a Nx4 matrix. This is very slow though. What is the fastest way to do this?

답변 (1개)

Sean de Wolski
Sean de Wolski 2015년 3월 20일
Use a cell to store each loops' results and then combine them with M all at the end:
M=[4 3 2 1;1 2 3 4];
C = cell(t,1); % empty contained
for ii = 1:t
C{ii} = createNewMatrix; % insert piece
end
Mcomplete = [M;cell2mat(C)]; % stack with M
  댓글 수: 2
Alex
Alex 2015년 3월 20일
but i have to use M within the loop...
James Tursa
James Tursa 2015년 3월 20일
편집: James Tursa 2015년 3월 20일
If you have to use M within the loop, then you will have to build a potentially different size M with each iteration. That means a data copy at each iteration, which can be slow if you have a lot of iterations. There is nothing much you can do about this directly at the m-file level.
There is a mex solution to this if your data was appended by columns instead of rows, but it is not trivial to apply. Make a large matrix M_large to store the largest M that you anticipate. At each iteration you do the following:
- Clear M (gets rid of the shared data copy of M_large)
- Fill in the newM stuff into M_large (Nx4 data copy which needs to be done regardless)
- Set M = M_large (shared data copy, not deep data copy, so very fast)
- Call a mex routine to call mxSetN on the M matrix to set the number of columns of M directly (done in place and safe, no data copy involved so very fast).
- Use M as a read-only matrix in your loop (changing M will cause a deep data copy which you don't want)
It is a bit tricky to implement to avoid the deep data copies of large amounts of data repeatedly, but can be done. Let me know if you want to look into this further (but note that it will not work in your current setup because you append rows instead of columns).

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

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by