当达到固定值时,将矢量转换为矩阵

时间:2018-02-15 20:09:40

标签: matlab matrix vector

这个问题是对此问题的补充:Link to original question 我怎样才能在代码中实现所有行都应该“填充”0,让我们说到第6列。

这是它应该如何运作的一个例子。

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]

2 个答案:

答案 0 :(得分:0)

以下是输入:

% minimum number of columns in the result matrix
min_cols = 6;

% the output from the accepted answer to your original question
result = [ ...
    8000 15000 15500 16000 ;
    16500 14000 0 0 ;
    9000 12000 13000 0];

以下是您可以执行的添加零的操作(将此代码附加到原始问题的已接受答案):

% number of columns to add (if min_cols < number of columns in result,
% will not add any extra columns)
cols_to_add = max(0, min_cols - size(result, 2));

% pad with zeros
result = [result, zeros(size(result, 1), cols_to_add)];

答案 1 :(得分:0)

您应该修改以下答案:

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

添加以下行以检查col_num是否超过6

if col_num == 7
    new_row = 1
end

最后,检查result的列大小是否不是6,修改result矩阵,如下所示:

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