How to flip non-zero elements of an array and keep zero elements at initial position?
Show older comments
I have an array (A) with non-zero elements and zero elements.
I want to flip all non-zero elements of A but keep all zero elements at their initial position to get B.
I tried this and it works but I am sure there is a one-liner-ish solution to my problem:
A = [1 2 3 4 5 0];
nz = nnz(A); %nz=5
N = numel(A); %N=6
numZend = N-nz; %numZend = 1
Zend = zeros(numZend); %Zend = 0
A1 = flip(nonzeros(A));%A1 = [5 4 3 2 1]'
B = [A1',Zend]; %B = [5 4 3 2 1 0]
Note that my zero elements are always at the end of my array. I can have 0 to 5 zero elements at the end of my array. Normally, length(A) ranges between 17 and 22.
Thank you :)
2 Comments
Give a general example. I have no idea how you can flip non-zero numbers if they are randomly located in a matrix. If you flipped the value right-to-left so that col now goes to (totalColumns-col+1) then it might happen that a non-zero number would like right exactly on top of a zero (which is not allowed to move). Like
m = randi([0, 9], 5, 10)
What would be the desired output for that matrix?
Accepted Answer
More Answers (3)
David Hill
on 8 Mar 2022
A = [1 2 3 4 5 0];
a=flip(A(A~=0));
a=[a,zeros(1,length(A)-length(a))];
1 Comment
I'm sure there's something simpler, but this is what my sleeplessness created:
A = [1:5 0; 11:14 0 0; 21:23 0 0 0; 31 0 32 0 33 0];
A = A.';
mask = A~=0;
B = zeros(size(A));
B(flipud(mask)) = A(mask);
B = flipud(B).'
Does this do what you want:
% Generate sample data.
A = zeros(6, 10);
for row = 1 : size(A, 1)
numNonZeros = randi([3,7]); % Between 3 and 7 non-zeros to start each row.
A(row, 1:numNonZeros) = randi(9, 1, numNonZeros);
end
A
% Now we have A, let's flip the non-zeros row-by-row
AFlipped = zeros(size(A));
for row = 1 : size(A, 1)
lastCol = find(A(row,:) ~= 0, 1, 'last');
AFlipped(row, 1:lastCol) = fliplr(A(row, 1:lastCol)); % Do the flip of non-zeros ONLY
end
AFlipped % Show in command window.
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!