当您在Matlab中循环时,从一个矩阵查找到另一个矩阵

时间:2015-01-28 14:35:08

标签: matlab

我有一个我创建的矩阵,它最初是一个列向量

matrix1 = [1:42]'

我有另一个矩阵,为了论证,一个名为matrix2的2000乘2矩阵 matrix2的第1列将始终是1到42之间的数字,并且可以按任何顺序排列。

我想循环遍历matrix2第1列并使用matrix1 column2的结果填充matrix2第2列与相应的数字 - 在循环的每次迭代结束时I&# 39;我要总结matrix2的第2列。

所以在伪代码中它会是这样的:

for i = 1:length(matrix2)
    look at i,1  its a "4" for example - take matrix2 column2
    and populate matrix1 next to the 4
    (ie column 2 in matrix 1 next to the 4 with this number)

所以矩阵1最初

1
2
3
4
5
6

矩阵2

3    100
1    250
2    200
1    80
4    40
5    50

所以在一次迭代后,matrix1看起来像这样

1   
2
3   100
4
5
6

迭代后2,matrix1看起来像这样

1   250
2
3   100
4
5
6

在迭代3之后,matrix1看起来像这样

1   250
2   200
3   100
4
5
6

如上所述,我会在每次迭代后执行计算,但重要的是填充矩阵1 column2。在matrix1 column2中显然会有很多写入或替换数字,但这很好,因为我会在每次迭代后执行计算。

1 个答案:

答案 0 :(得分:0)

试试这个:

    for ii =1:length(matrix2)
       matrix1(matrix2(ii,1),2) = matrix2(ii,2);
    end

可能需要从一开始就制作matrix1 2D(只需将第二列初始化为全0)。

相关问题