【问题标题】:Matlab - how to create matrix from two or more vectors, which represents every combination of a single element from each vector [duplicate]Matlab - 如何从两个或多个向量创建矩阵,它表示每个向量中单个元素的每个组合[重复]
【发布时间】:2019-03-07 00:43:25
【问题描述】:

我是 matlab 新手,有一个关于如何有效地从两个或多个向量创建矩阵的问题,其中每个向量中单个元素的每个组合都表示在结果矩阵中。

例如,假设我们有向量:

x = [1 2 3 4];  y = [5 6 7 8];

我想在矩阵 ans 中得到以下结果:

ans = [1 5; 1 6; 1 7; 1 8; 2 5; 2 6; 2 7; ... 4 7; 4 8]

上述示例适用于二维(两个输入向量),但如果解决方案适用于 d 维(输入向量的 d 个数),则它会是理想的。谢谢!

【问题讨论】:

    标签: matlab matrix vector


    【解决方案1】:
    [X,Y] = ndgrid(x,y);
    desiredOutput = [X(:),Y(:)];
    

    【讨论】:

    • 请解释你的代码。
    • 这只适用于两个向量
    【解决方案2】:

    这是 d 维度的解决方案。

    %% Input.
    x = [1 2 3 4];
    y = [5 6 7 8];
    
    
    %% Fixed 2d solution as provided by Alex.
    [X, Y] = ndgrid(x, y);
    desiredOutput = [X(:), Y(:)]
    
    
    %% Arbitrary dimension solution.
    
    % Store all input vectors in cell array.
    vectors{1} = x;
    vectors{2} = y;
    
    % Initialize output for ndgrid.
    VECTORS = cell(numel(vectors), 1);
    
    % Call ndgrid with arbitrary number of vectors.
    [VECTORS{:}] = ndgrid(vectors{:});
    
    % Convert VECTORS.
    VECTORS = cellfun(@(x) x(:), VECTORS, 'UniformOutput', false);
    
    % Output.
    desiredOutput = [VECTORS{:}]
    
    
    %% Expanded input.
    z = [9 10 11 12];
    vectors{3} = z;
    VECTORS = cell(numel(vectors), 1);[VECTORS{:}] = ndgrid(vectors{:});
    VECTORS = cellfun(@(x) x(:), VECTORS, 'UniformOutput', false);
    desiredOutput = [VECTORS{:}]
    

    【讨论】:

    • 漂亮!谢谢 - 它运作良好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-28
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    相关资源
    最近更新 更多