2013-08-04 59 views
0

我試圖產生一個輸出,它將採用數組的最後一個值,然後用在該數組中找到的下一個最低值開始下一個數組。如果沒有下一個最低值,我希望它結束​​循環請參閱我想要得到的答案示例。使用matlab/octave使用circshift進行數組操作

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 

任何想法如何解決這一問題?

謝謝

回答

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 
+0

,如果有,我想剛剛結束的循環中沒有一個最低值 –

+0

我已經更新了我的解決方案相應 –

+0

這少了點一遍又一遍的連續循環 –

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