2
votes

So I want to concatenate an m x n matrix to obtain a 1 x mn matrix. The matrix I want to concatenate are generated from a while loop. Although the number of columns will always be 3, I however cannot tell how many rows there will be for each iteration. Also, the row sizes for each iteration may not always be the same.

The code runs in cases where the row sizes were all equal to 6, but in cases where they aren't equal I get an error:

Error using vertcat Dimensions of matrices being concatenated are not consistent.

parts of the code are as follows:

A = [];
B = [];
searchArea = 2;

for ii = 1: numel(velocity)
    Do ....
    while area(ii,:) < searchArea
        Do ....
        % COLLATE vectors for A
        A = [A; [Ax(ii), Ay(ii), Az(ii)]];
        Do ...
    end
    %# Copy the A into new variable (B) and Reshape into row vector so as to associate each row to its corresponding velocity
    B = [B; reshape(A.',1,[])];
    A = [];
end

Could someone please advice me on what I am doing wrong here. I would clarify further if there be need. Thanks guys!

1
Usually, we use cell arrays to store arrays of different sizes. - O'Neil
Thanks @O'Neil. I was initially trying to avoid using cell arrays. In any case, when i try creating a cell array for storage as follows: A = cell(numel(velocity), 1); and then within the loop i have: B = [B; A]; i encounter two issues: 1) the loop stops (without any error message) once it encounters an array with more rows than the preceding iterations. 2) rather than start storing B from index 1 it begins from index 101 (velocity is from 1-100). Any ideas what's wrong here as well? - User110
Oh i see my wrong: that should be B{ii} = A;. It works now! Maybe i should just stick with the cell array. Thanks a bunch! - User110

1 Answers

0
votes

If it's your intent that B ends up being a row vector, then you need to change this:

B = [B; reshape(A.',1,[])];  % Does vertical concatenation

to this:

B = [B reshape(A.',1,[])];  % Does horizontal concatenation (note there's no semicolon)

so that each row vector gotten from reshaping A gets added to the end of the row instead of as a new row (as the semicolon indicates).