concatenate different matrices with different dimensions

71 次查看(过去 30 天)
Hello, I am obtaining 3 matrices with two colums each of then (the first column contains the time and the second column contains the acceleration) that represents the acceleration components of earthquake signals that can be represented as X, Y and Z matrices. So, these matrices may have the following size: X (520x2), Y(480x2) and Z(500x2) as an example. If I want to concatenate the matrices horizontally using this command:
data = horzcat(X,Y,Z), it will not work as they have different sizes.
The final size of the matrix (data) should be 520x6 (based on the highest length of colums of the three matrices X,Y and Z). So, zeros should be added at the end of each matrix with lower column size convert Y(480x2) and and Z(500x2) into Y(520x2) and Z(520x2) and then the three matrices be concatenated horizontally to create the matrix data(520x6). Thank you for your help.

采纳的回答

Shantanu Dixit
Shantanu Dixit 2023-6-29
编辑:Shantanu Dixit 2023-7-1
Hi Jorge,
Yes you are right, horzcat requires the number of rows to be the same and for that padding needs to be done as you've explained in your question.
  • Max number of rows among the three matrices are 520 or can be found through as well
maxRows = max([size(X, 1), size(Y, 1), size(Z, 1)]);
  • Pad the matrices Y and Z with zeros at the end to match the maximum number of rows using the padarray() function, Since zeros need to be added at the end you need to use 'post' as the argument.
Y = padarray(Y, [maxRows - size(Y, 1), 0], 'post');
Z = padarray(Z, [maxRows - size(Z, 1), 0], 'post');
  • Number of rows are same now, use horzcat to concatenate the matrices horizontally.
Refer to the documentation:

更多回答(1 个)

Sushma Swaraj
Sushma Swaraj 2023-6-29
Hi,
Assuming you have X,Y and Z matrices with different sizes:
% Determine the maximum no.of rows among X,Y and Z
maxRows = max([size(X, 1), size(Y, 1), size(Z, 1)]);
% Create zero matrices to match the no.of rows
Y_zeros = zeros(maxRows, size(Y, 2));
Z_zeros = zeros(maxRows, size(Z, 2));
% Assign the original data to the zero matrices
Y_zeros(1:size(Y, 1), :) = Y;
Z_zeros(1:size(Z, 1), :) = Z;
% Concatenate X,Y_zeros and Z_zeros horizontally
data = horzcat(X, Y_zeros, Z_zeros);
Hope it helps!

类别

Help CenterFile Exchange 中查找有关 Agriculture 的更多信息

产品


版本

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by