2014-11-24 176 views
1

我有這樣的一個變量,它是所有一行移動號碼的新行:Matlab-如果條件滿足

​​

我想寫一個for循環,會發現其中數小於前一個,把數字的休息,新行,這樣

1 2 3 4 5 6 7 8 9 
2 4 5 6 
5 

我已經試過這樣:

test = [1 2 3 4 5 6 7 8 9 2 4 5 6 5]; 
m = zeros(size(test)); 
for i=1:numel(test)-1; 
    for rows=1:size(m,1) 
    if test(i) > test(i+1); 
    m(i+1, rows+1) = test(i+1:end) 
    end % for rows 
end % for 

但它顯然是不正確的,只是掛起。

回答

3

x是您的數據載體。你想,可以很簡單地做什麼如下:

ind = [find(diff(x)<0) numel(x)]; %// find ends of increasing subsequences 
ind(2:end) = diff(ind); %// compute lengths of those subsequences 
y = mat2cell(x, 1, ind); %// split data vector according to those lenghts 

這產生單元陣列y期望的結果。使用單元格數組,以便每個「行」可以具有不同數量的列。

例子:

x = [1 2 3 4 5 6 7 8 9 2 4 5 6 5]; 

y{1} = 
    1  2  3  4  5  6  7  8  9 
y{2} = 
    2  4  5  6 
y{3} = 
    5 
2

如果你正在尋找一個數字陣列輸出,您將需要填補「空白」的東西,並與zeros填充似乎是一個好選項,就像你在代碼中做的那樣。

所以,這裏有一個bsxfun基礎的方法來達到同樣的 -

test = [1 2 3 4 5 6 7 8 9 2 4 5 6 5] %// Input 
idx = [find(diff(test)<0) numel(test)] %// positions of row shifts 
lens = [idx(1) diff(idx)] %// lengths of each row in the proposed output 
m = zeros(max(lens),numel(lens)) %// setup output matrix 
m(bsxfun(@le,[1:max(lens)]',lens)) = test; %//'# put values from input array 
m = m.' %//'# Output that is a transposed version after putting the values 

輸出 -

m = 
    1  2  3  4  5  6  7  8  9 
    2  4  5  6  0  0  0  0  0 
    5  0  0  0  0  0  0  0  0