【问题标题】:Lookup from one matrix into another as you loop through in Matlab在 Matlab 中循环时从一个矩阵查找到另一个矩阵
【发布时间】:2015-03-27 12:10:45
【问题描述】:

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

matrix1 = [1:42]'

我有另一个矩阵,它是一个 2000×2 矩阵,称为 matrix2
matrix2 的第 1 列将始终是 1 到 42 之间的数字,并且顺序不限。

我想遍历matrix2 第 1 列,并用来自matrix2 column2 的结果填充matrix1 第 2 列与相应的数字 - 在循环的每次迭代结束时,我将总结第 2 列矩阵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 列 2。显然,matrix1 column2 中的数字会有很多重写或替换,但这很好,因为我将在每次迭代后执行计算。

【问题讨论】:

    标签: matlab


    【解决方案1】:

    试试这个:

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

    可能需要从一开始就将 matrix1 设为 2D(可以将第 2 列初始化为全 0)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-11
      • 2022-11-21
      • 1970-01-01
      • 1970-01-01
      • 2013-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多