将向量转换为矩阵:当值>时为新行X [英] Convert vector into matrix: New row when value > X
问题描述
我有一个问题,但找不到任何解决方案,我的问题是我有一个向量V (m x 1)
. V
是从excel导入的数据,长度可能有所不同.它包含数字序列> 7000和数字序列< 7000. 7000.序列的长度也可以不同.现在,我要将所有大于7000的值复制到矩阵中.每次V
的值> 7000时,矩阵都应开始新的一行.为了使矩阵的新行的长度不变,应将较短的行用0填充",直到达到最长的行的长度.
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]`
我想到的是,每次V
的值> 7000时,首先将向量分成几个较小的向量.然后将它们组合到所需的矩阵中,并删除所有< 7000.但这对我来说似乎很不方便.
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.
推荐答案
解决方案可以使用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
为true,则在此之前创建行,而在创建行之后没有V(j) < limit
.
case 1
is true if before this a row is created and there is no V(j) < limit
after the row creation.
case 2
在此V(idx-1) < limit)
之前,则为true.如果V(idx) <= limit
,则case 3
为true.
case 2
is true if before this V(idx-1) < limit)
. and case 3
is true if V(idx) <= limit
.
这篇关于将向量转换为矩阵:当值>时为新行X的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!