MATLAB: Combining matrices by replacing zeros matrices I have two matrices of the same length; A = [1 ,0, 2, 0, 3, 0, 5]; B = [0, 2, 0, 3, 0, 5, 0]; I want to be 'combine' them into one matrix where the zeros 'disappear'; C = [1, 2, 2, 3, 3, 5, 5]; May I know how to do this? Best Answer A = [1 ,0, 2, 0, 3, 0, 5];B = [0, 2, 0, 3, 0, 5, 0];C = A + BOr if the zeros need not be at the same indices as the non-zeros in the other variable:C = A;C(A == 0) = B(B ~= 0) Related SolutionsMATLAB: How can I add zeros elements to a matrix Hi Moein,there are different ways to do this. One of which is to define a fully zero matrix with all zerosnewMatrix = zeros(5,5); % all zero matrixThen assign the non zero elements.newMatrix(1:3,1:3) = oldMatrix; % oldMatrix is a, newMatrix is bThis is one way to do it.Another way would be to concatenate the oldMatrix with zeros.neMatrix_1 = [oldMatrix,zeros(3,2)]; % horizontal concatenationnewMatrix_2 = [newMatrix_1;zeros(2,5)]; % vertical concatenationThis should give you the same in newMatrix_2 MATLAB: Construct a lower triangular matrix with smaller matrices A = [1 2; ... 3 4; ... 5 6];B = tril(ones(4,3), -1);R = kron(B, A)R = [0, 0, 0, 0, 0, 0; ... 0, 0, 0, 0, 0, 0; ... 0, 0, 0, 0, 0, 0; ... 1, 2, 0, 0, 0, 0; ... 3, 4, 0, 0, 0, 0; ... 5, 6, 0, 0, 0, 0; ... 1, 2, 1, 2, 0, 0; ... 3, 4, 3, 4, 0, 0; ... 5, 6, 5, 6, 0, 0; ... 1, 2, 1, 2, 1, 2; ... 3, 4, 3, 4, 3, 4; ... 5, 6, 5, 6, 5, 6] Related QuestionHow can i solve this problem ? its easy but i dont know!Separating Matrix by Column By PatternHow can i put all zeros in the end of the rows in a matrixHow to return the sequential number of nonzero and zero elements in a listHow to convert A=[1 3 2] to B= [ 1 0 0;0 0 3;0 2 0]Reset value in cumsum matrix when reachin limit, and move the value to another matrixRemoving zeros from columnI have two matrices that are related and I need to sort one matrix while sorting the corresponding matrix the same way.
Best Answer