1

I wish to append a row-vector (and later, also a column vector) to an existing x by y by z matrix. So basically "Add a new row (at the "bottom") for each z in the original 3d matrix. Consider the following short Matlab program

appendVector = [1 2 3 4 5]; % Small matrix for brevity. Actual matrices used are much larger.
origMatrix   = ones(5,5,3);
appendMatrix = [origMatrix( ... ); appendVector];

My question is: How do I adress (using Matlab-style matrix adressing, not a "manual" C-like loop) origMatrix( ... ) in order to append the vector above? Feel free to also include a suggestion on how to do the same operation for a column-vector (I am thinking that the correct way to do the latter is to simply use the '-operator in Matlab).

2
  • 1
    How exactly do you intend to append a 5-element vector to a 3D matrix. You would need a 1 x 5 x 3 array because you need to fill the third dimension. Commented Jul 9, 2016 at 14:37
  • @Suever I assumed that as part of the eventual solution. Is there a way to perform this operation using only a vector (by having Matlab take care of additional dimensions) or do I have to "prepare" the appended vector to instead be a 3d array (as per your suggestion above) prior to appending? Commented Jul 9, 2016 at 14:41

1 Answer 1

1

A "row" in a 3D matrix is actually a multi-dimensional array.

size(origMatrix(1,:,:))
%   5   3

So to append a row, you would need to append a 5 x 3 array.

toAppend = rand(5, 3);
appendMatrix = cat(1, origMatrix, toAppend);

You could append just a 5 element vector and specify an index for the third dimension. In this case, the value for the "row" for all other indices in the third dimension would be filled with zeros.

appendVector = [1 2 3 4 5];
origMatrix = ones(5,5,3);

appendMatrix = origMatrix;
appendMatrix(end+1, :, 1) = appendVector;

If instead, you want to append the same vector along the third dimension, you could use repmat to turn your vector into a 1 x 5 x 3 array and then append that.

appendVector = repmat([1 2 3 4 5], 1, 1, size(origMatrix, 3));
appendMatrix = cat(1, origMatrix, appendVector);
Sign up to request clarification or add additional context in comments.

2 Comments

Wonderful. Spot on.
A short note regarding your segment on the use of repmat. The code you present gives the error: "Error using cat Dimensions of matrices being concatenated are not consistent." I have not investigated why that is since the prior suggestion (not using repmat) was sufficient to solving my problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.