[英]Array manipulation with matlab / octave using 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
任何想法如何解決這一問題?
謝謝
懶得看您的代碼。 這個怎么樣?
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
我只需要在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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.