Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
265 views
in Technique[技术] by (71.8m points)

matlab - Turn vector into matrix when a fixed value is reached

This question is an addition to this one: Link to original question How can I implement in the code, that all rows should be "filled up" with 0 let's say up to column 6.

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 0 0] 
2.row [16500 14000 0 0 0 0] 
3.row [9000 12000 13000 0 0 0]
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You should modify the answer likes the following:

result = []; new_row = 1; col_num = 1; row_num = 0;
limit = 7000;
for idx = 1:length(V)
    if col_num == 7
        new_row = 1
    end
    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
if size(result,2) < 6
    result(1,6) = 0;
end

Add the follwoing lines to check the col_num does not exceed from 6:

if col_num == 7
    new_row = 1
end

At the end, check if the column size of the result is not 6, modify the result matrix likes the following:

if size(result,2) < 6
    result(1,6) = 0;
end

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...