MATLAB: Non Zero element appear first with keeping the same size of the matrix MATLAB A = [1 0 2 3;2 0 0 5; 3 0 0 1; 0 0 1 5]; How The matrix will be transformed like this (No-zero element will come first, row wise) A = [1 2 3 0; 2 5 0 0; 3 1 0 0; 1 5 0 0] Best Answer solution :A = [1 0 2 3;2 0 0 5; 3 0 0 1; 0 0 1 5];A(A==0)=nan;A=sort(A,2);A(isnan(A))=0;disp(A) Related SolutionsMATLAB: How to fill values between two values. You could use interp1:>> A = [1,0,0,0,2,0,3,0,0,0,0,4,0,5];>> X = find(A);>> B = interp1(X,A(X),1:numel(A))B = 1.0000 1.2500 1.5000 1.7500 2.0000 2.5000 3.0000 3.2000 3.4000 3.6000 3.8000 4.0000 4.5000 5.0000 MATLAB: Split a matrix into smaller matrices based on another variable If you have multiple 1s in a row of your B matrix, then creating variable names like C, D, .. is not advisible: https://www.mathworks.com/matlabcentral/answers/304528-tutorial-why-variables-should-not-be-named-dynamically-eval. It is better to use cell arry.Try the following codeA = [1 2 3 4 5; 1 2 3 4 5; 1 2 3 4 5; 1 2 3 4 5; 1 2 3 4 5];B = [1 0 1 0 0; 1 0 1 0 0; 1 0 1 0 0; 1 0 1 0 0; 1 0 1 0 0];grps = cumsum(B, 2);C = cell(size(A,1),1);for i = 1:numel(C) C{i} = splitapply(@(x) {x}, A(i,:), grps(i,:));endIf number of 1s are equal in each row then you can also run the followingC = reshape([C{:}], [], numel(C)).'; Related QuestionHow to combine vectors of different length into matrixCombining matrices by replacing zerosHow to delete a row in a matrixReshape cell array into a matrix2D interpolation of scattered data
Best Answer