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

2 次查看(过去 30 天)
Here is the problem i am trying to work with:
Develop a user-de
  5 个评论
per isakson
per isakson 2014-11-6
编辑:per isakson 2014-11-9
@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

请先登录,再进行评论。

回答(1 个)

per isakson
per isakson 2014-11-6
编辑:per isakson 2014-11-6
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 个评论
per isakson
per isakson 2014-11-9
编辑:per isakson 2014-11-9
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 2014-11-10
编辑:per isakson 2014-11-11
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

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Entering Commands 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by