Append matrix to another matrix in Matlab

17 次查看(过去 30 天)
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