Need help flipping elements in an array without using built in functions

2 views (last 30 days)
Here is the problem i am trying to work with:
Develop a user-de
  5 Comments
per isakson
per isakson on 6 Nov 2014
Edited: per isakson on 9 Nov 2014
@Image Analyst, Given Walter's rules, isn't it impossible to write a bubble-sort routine? I assume that's the task. Is &nbsp + &nbsp to be regarded as syntactic sugar for the function &nbsp plus

Sign in to comment.

Answers (1)

per isakson
per isakson on 6 Nov 2014
Edited: per isakson on 6 Nov 2014
Hint:
vec = 1:12;
ix = 6;
vec = vec( [(1:ix-2),ix,ix-1,(ix+1:end)] )
vec =
1 2 3 4 6 5 7 8 9 10 11 12
The fifth and sixth elements are flipped.
&nbsp
I'm a big fan of the debugging tools of Matlab! Here are some links on debugging in Matlab
  15 Comments
per isakson
per isakson on 9 Nov 2014
Edited: per isakson on 9 Nov 2014
Try the following steps
  • describe exactly what the algorithm shall do. ... given input ..., produce output. Ascending or descending?
  • describe in words how you envision that the algorithm shall work
  • use pseudo code to describe the algorithm
  • return to your Malab code
  • step through a couple of really simple examples
per isakson
per isakson on 10 Nov 2014
Edited: per isakson on 11 Nov 2014
I run your code. There are obviously problems. Do the following:
  • Put breakpoints at the lines after the two last &nbsp disp( * )
  • Step through the code with the double green arrow,[Continue].
>> list = randi( 12, [1,6] );
>> list = reflip( list )
9 10 4 9 8 2
10 9 4 9 8 2
18 reflip = [flip(end-k+1:-1:1), flip(end-k+2:end)];
2 8 9 4 9 10
8 2 9 4 9 10
9 4 9 2 8 10
4 9 9 2 8 10
2 9 9 4 8 10
9 2 9 4 8 10
9 2 9 4 8 10
2 9 9 4 8 10
9 2 9 4 8 10
2 9 9 4 8 10
2 9 9 4 8 10
list =
2 9 9 4 8 10
>>
where
function vec = reflip( vec )
%{
list = randi( 12, [1,6] );
list = reflip( list )
%}
maximum=0;
disp( vec )
for k=1:numel(vec)
for ii=1:numel(vec)
if maximum < vec(ii)
maximum = vec(ii);
max_index=ii;
end
end
flip = [vec(max_index:-1:1), vec(max_index+1:end)];
disp( flip )
reflip = [flip(end-k+1:-1:1), flip(end-k+2:end)];
disp( reflip )
vec = reflip;
end
end

Sign in to comment.

Categories

Find more on Entering Commands 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!