Clear Filters
Clear Filters

Append matrix to another matrix in Matlab

15 views (last 30 days)
Alex
Alex on 20 Mar 2015
Edited: James Tursa on 20 Mar 2015
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?

Answers (1)

Sean de Wolski
Sean de Wolski on 20 Mar 2015
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 Comments
Alex
Alex on 20 Mar 2015
but i have to use M within the loop...
James Tursa
James Tursa on 20 Mar 2015
Edited: James Tursa on 20 Mar 2015
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).

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!