How to reorder a vector one cell at a time?
2 views (last 30 days)
Show older comments
I am looking to create a matrix by iteratively swapping one row with another in a vector. For example, I want to start with [1 1 3 4 1]' and end with
1 1 1 1 3 3
1 1 3 3 1 4
3 3 1 4 4 1
4 4 4 1 1 1
1 1 1 1 1 1
where each column is a different iteration and I am only moving a single 1 at a time. I was able to figure out a case with a single 1.
order = [1 3 4 1]'
for i = 1:3
if order(i) == 1
order([i i+1]) = order([i+1 i]);
ord(:,i+1) = order;
end
end
3 Comments
James Tursa
on 24 Feb 2021
Isn't this just a variation of a bubble sort where you are only moving the 1's?
Answers (2)
David Hill
on 24 Feb 2021
order = [1 3 1 5 1 1 7 1 8 1 1 9 4 1]';
a=order([find(order~=1);find(order==1)]);
c=1;
while ~isequal(order(:,c),a)
c=c+1;
order(:,c)=order(:,c-1);
for i = 1:size(order,1)-1
if order(i,c) == 1&&order(i+1,c)~=1
order(i:i+1,c) = order(i+1:-1:i,c);
break;
end
end
end
0 Comments
Walter Roberson
on 24 Feb 2021
Edited: Walter Roberson
on 24 Feb 2021
Okay, so the problem is that the rules are not exactly as you describe.
The algorithm
- Start at the top of the column, and remember the fact that you started from the top
- look down the column for the first 1
- check to see if everything from that 1 to the bottom is 1
- if so and you have marked that you started from the top, then you are done moving everything so exit the algorithm
- if everything was 1 and you have not marked that you started from the top, then go back to step 1 (starting from the top again)
- to get here, not everything from the 1 downward is a 1. unmark that you started from the top. Now bubble that 1 "downward" one row at a time, stopping when everything from the position of moved 1 to the end is all 1's
- go back to the start of the column (you only reach this step if you were bubbling a 1 downward)
When you reach the end, all 1's will be at the bottom of the column.
Note: When you are bubbling a 1 downward, exchanging it with a different 1 is a valid step. That is why your second column looks the same as the first column: the 1 at the top got logically exchanged with the 1 below it, and column 3 is moving the 1 even further down.
0 Comments
See Also
Categories
Find more on Loops and Conditional Statements 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!