Convert vector into matrix: New row when value > X

2019-07-25 20:58发布

问题:

I have a question and I can't find any solution, My problem is, that i have a vector V (m x 1). V is imported data from excel and can differ in leangth. It contains sequences of numbers >7000 and sequences of numbers < 7000. The sequences also can differ in leangth. Now I want to copy all values that are >7000 into a matrix. Everytime the value of V gets >7000 the matrix should start a new row. So that the new rows of the matrix won't differ in leangth, the shorter rows should be "filled up" with 0 until the leangth of the longest row is reached.

This is an example of how it should work.

`V [18x1]: [6000, 6500, 5000, 8000, 15000, 15500, 16000, 6000, 4000, 16500, 14000, 400, 5000, 6000, 9000, 12000, 13000, 5000]`

`Matrix [3x4]: 
1.row [8000 15000 15500 16000] 
2.row [16500 14000 0 0] 
3.row [9000 12000 13000 0]`

I thought of first splitting the vector into several smaller vectors each time the value of V gets > 7000. And afterwards combining them to the desired matrix and delete all values < 7000. But this seems quite inconvenient to me.

回答1:

A solution can be using for:

result = []; new_row = 1; col_num = 1; row_num = 0;
limit = 7000;
for idx = 1:length(V)
    if(V(idx) > limit && new_row == 0) % case 1
        result(row_num, col_num) = V(idx);
        col_num = col_num + 1;
    elseif(V(idx) > limit && new_row == 1) %case 2
        row_num = row_num + 1; new_row = 0; col_num = 2;
        result(row_num, 1) = V(idx);
    elseif(V(idx) <= limit) %case 3
         new_row = 1;
    end
end

case 1 is true if before this a row is created and there is no V(j) < limit after the row creation.

case 2 is true if before this V(idx-1) < limit). and case 3 is true if V(idx) <= limit.