【问题标题】:Rearranging vectors into matrix将向量重新排列成矩阵
【发布时间】:2016-06-18 15:35:17
【问题描述】:

我有数据,按以下顺序排列

现在您可以看到每个x 值都有不同的y 值,并且分别有一些real 和img 值。 x 具有维度 m x 1y 具有维度 n x 1。现在我想在一个新矩阵中排列数据,使新矩阵的维度为m x n。换句话说,x 将是我的行,y 的值将是我的列,相应地,对于每个 xy,该值将按如下方式进入新矩阵。

new_matrix(m,n)= real*exp{img}

即对于每个xy 值,实部应乘以虚部的指数并进入新矩阵。

【问题讨论】:

    标签: matlab matrix


    【解决方案1】:

    MATLAB 使用列优先索引,因此如果您创建一个矩阵 m x n 然后填充它,它将先填充行,然后填充列。您是按行主要顺序排列的(如果不是,我们可以使用sortrows 来确保它是)。然后我们可以使用最后两列计算real * exp(imag),并将其重塑为n x m,然后将其转置以获得您的m x n 矩阵。

    data = [0   1   25  12
            0   2   15  26
            1   1   78  26
            1   2   25  63
            2   1   26  35
            2   2   45  63
            3   1   56  26
            3   2   48  2];
    
    % Ensure that the data is in the correct order
    data = sortrows(data);
    
    % Determine the size of the output matrix
    m = numel(unique(data(:,1)));
    n = numel(unique(data(:,2)));
    
    % Compute real * exp(imag) and make it the correct shape
    out = reshape(data(:,3) .* exp(data(:,4)), n, m).';
    
    %   4.0689e+06   2.9359e+12
    %   1.5267e+13   5.7345e+28
    %   4.1236e+16   1.0322e+29
    %   1.0961e+13   3.5467e+02
    

    【讨论】:

      【解决方案2】:

      你得到的是一个矩阵的稀疏表示。使用稀疏构造函数是获取矩阵的最简单(但可能不是最快)的方法:

      full(sparse(data(:,1)+1,data(:,2),data(:,3) .* exp(data(:,4))))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-04-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多