To change value based on algorithm

1 view (last 30 days)
yue ishida
yue ishida on 31 Aug 2012
Hi and Salam.
I have a matrix as below:
A =
[11 1 11 11 11 11 11;
11 22 1 11 11 11 11;
11 11 11 1 33 11 11;
22 22 22 11 1 11 22;
11 33 11 11 11 1 33;
33 22 22 22 22 33 1;
1 11 33 22 22 22 11]
I need help to change value in a matrix based on algorithm as below:
1. If a row has one 33 value, the value will be swapped with value before before value 1. For example, in 3rd row, the row will become as below:
11 11 33 1 11 11 11
2. If a row has more than one value 33, the the first value of 33 from the left will swap with value before 1. The next value 33 will swap with value before first value 33. This will also happen to the next value of 33. For example as in row 5:
11 11 11 33 33 1 11
3. If value before 1 already value 33, this value will fix. If a row has more than one value 33, the the first value of 33 from the left will swap with 2nd value before 1. This will also happen to the next value of 33. For example as in row 6:
22 22 22 22 33 33 1

Answers (1)

Image Analyst
Image Analyst on 31 Aug 2012
Seems like a complicated crazy thing to do, but I'm sure it's well within your capabilities especially if I give you these useful hints:
a33 = (A==33) % Map of where 33's occur.
% Get a vector of which rows have 33.
rowsWith33 = any(a33, 2)
I think you should be able to handle it from there. You might also want to learn about ind2subs(), subs2ind(), find(), and linear indexing for alternative ways to approach it. Write back if you can't figure it out from here.

Categories

Find more on Resizing and Reshaping Matrices 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!