How to flip non-zero elements of an array and keep zero elements at initial position?
9 次查看(过去 30 天)
显示 更早的评论
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 个评论
Image Analyst
2022-3-8
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?
采纳的回答
Les Beckham
2022-3-8
Another possibility (still requires a loop):
A = [ 134 159 122 175 126 0 0
151 170 189 196 0 0 0
155 114 115 126 184 125 0 ]; % test data
B = zeros(size(A));
for i = 1:size(A, 1)
inz = A(i,:)~=0; % logical indices of non-zero elements
B(i,inz) = flip(A(i,inz)) % flip the non-zero elements in this row
end
1 个评论
Les Beckham
2022-3-8
编辑:Les Beckham
2022-3-8
If all rows of the array have the same number of columns of zeros it is possible to do this without the loop.
A = [ 134 159 122 175 126 0 0
151 170 189 196 125 0 0
155 114 115 126 184 0 0 ]; % test data -- modified
B = zeros(size(A));
[r, c] = find(A~=0);
B(A~=0) = fliplr(A(unique(r), unique(c)))
Not exactly pretty, but it works. I think I like the loop better since it works for different numbers of zeros in each row and is a little easier to follow.
更多回答(3 个)
Image Analyst
2022-3-8
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.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!