使用circshift使用matlab / octave进行数组操作

时间:2013-08-04 16:13:44

标签: arrays matlab sorting octave

我正在尝试生成一个输出,该输出将获取数组的最后一个值,然后使用该数组中找到的下一个最低值启动下一个数组。如果没有下一个最低值,我希望它只是结束循环参见我想要得到的答案示例。

9.0000   11.0000    5.0000    7.0000    3.0000    7.0100
7.0000    3.0000    7.0100    9.0000   11.0000    5.0000
3.0000    7.0100    9.0000   11.0000    5.0000    7.0000

我在下面使用的代码只能得到前两行的正确性,并在最后做任何想法如何解决这个问题。

代码:

clc
a=[9,11,5,7,3,7.01];
[a_sorted, a_idx] = sort(a, 2); %sorts array along with getting index values of numbers
a_sorted=a_sorted'; % sort into col
a_idx=a_idx'; % sort into col
a_val_idx=[a_sorted a_idx]; % combine array

loop_amount=length(find(a<a(end))) %how many values are less than the last value, loop this many times

for yy=1:loop_amount

    a_val=find(a_val_idx(:,1)<a(end)); %find idx of next lowest value from end 
    nxt_low_idx_val=a_val_idx(a_val(end),2) %get idx of the next lowest value from end

    b=circshift(a,[0 (length(a)-nxt_low_idx_val+1)])

    a=b;

end

我得到的结果是

loop_amount =  3
a =
    9.0000   11.0000    5.0000    7.0000    3.0000    7.0100

nxt_low_idx_val =  4
a =
    7.0000    3.0000    7.0100    9.0000   11.0000    5.0000

nxt_low_idx_val =  5
a =
   11.0000    5.0000    7.0000    3.0000    7.0100    9.0000

nxt_low_idx_val =  6

正如您所见,最后一行应为

nxt_low_idx_val =  2

3.0000    7.0100    9.0000   11.0000    5.0000    7.0000

任何想法如何解决这个问题?

由于

2 个答案:

答案 0 :(得分:1)

太懒了,看看你的代码。怎么样?

a = [9,11,5,7,3,7.01];
disp(' ')
disp(a) % display original value
len = length(a);

loop_count = sum(a<a(end)); % as per your code
for count = 1:loop_count
  b = a(1:end-1); % copy of a, will be overwritten
  b(b>a(end)) = NaN; % these values do not count
  if(all(isnan(b)))
    break % exit if there are no lower values
  end
  [aux ind] = max(b); % max of the remaing values
  perm = mod(ind+(0:len-1),len); % cyclic shift
  perm(perm==0) = len; % correct zero to len
  a = a(perm); % do the shift
  disp(a) % display new value
end

答案 1 :(得分:0)

我只需要在for循环下移动一些东西

clc
a=[9,11,5,7,3,7.01];


loop_amount=length(find(a<a(end))) %how many values are less than the last value, loop this many times

for yy=1:loop_amount
    [a_sorted, a_idx] = sort(a, 2); %sorts array along with getting index values of numbers
    a_sorted=a_sorted'; % sort into col
    a_idx=a_idx'; % sort into col
    a_val_idx=[a_sorted a_idx]; % combine array
    a_val=find(a_val_idx(:,1)<a(end)); %find idx of next lowest value from end 
    nxt_low_idx_val=a_val_idx(a_val(end),2) %get idx of the next lowest value from end

    b=circshift(a,[0 (length(a)-nxt_low_idx_val+1)])

    a=b;

end