【问题标题】:how to join N vectors into matrix in matlab?如何在matlab中将N个向量加入矩阵?
【发布时间】:2016-03-31 12:18:13
【问题描述】:

我尝试查找此内容,但真的不知道要查找什么...

我需要“表连接”N 个向量,意思是, 创建一个矩阵,其中每个输入向量都有一行,每个可能的条目都有一列。

如果有一个翻译向量可以很容易地访问哪个列负责哪个条目,那就太好了

例如

a = [3, 2, 4, 9]
b = [3, 1, 5, 9]
c = [2, 4, 9, 6]

然后

join(a, b, c) =
[
3;    2;   nan; 4;   nan; 9; nan,
3;    nan; 1;   nan; 5;   9; nan,
nan;  2;   nan; 4;   nan; 9; 6,
]

带有平移向量

[3,2,1,4,5,9,6]

因此,如果我发现有关第 i 列的信息,我可以很容易地知道该列代表什么。

我更喜欢 join 操作能够接受 n 个向量(它们可以是相同的长度),但 2 也可以。

此外,乍一看,这种数据表示在某些方面似乎有点多余。也许有更好的方法来表示“连接矩阵”

谢谢

【问题讨论】:

  • 你的例子没有意义,nans 来自哪里?你也读过tablesuk.mathworks.com/help/matlab/ref/table.html
  • @GameOfThrows 因为每一行代表一个输入向量,每列代表一个值,如果输入向量中不存在值,则为nan。我已经阅读过有关表格的信息,但如果可能的话,我更喜欢纯矢量解决方案。
  • 你的意思是翻译向量是[3,2,1,4,5,9,6] ?
  • 这仍然没有意义,以 a 为例,[3,2,4,9] 和 b [3,1,5,9] 的连接将是 [3,9]因为它们都有 3 和 9 的共同点。你在说什么加入
  • 绝对重要。如果顺序可以是anything,那么您需要一个额外的规则来确定如何生成平移向量,因为假设 3 总是在 2 的左侧是没有意义的。

标签: matlab join vector


【解决方案1】:

基本上,您希望按照接收顺序使用所有可能的唯一输入来构建您的翻译向量。为此,我们可以将所有输入连接在一起,而不是找到唯一值。

values = cat(1, [3, 2, 4, 9], [3, 1, 5, 9], [2, 4, 9, 6])
%//  3     2     4     9
%//  3     1     5     9
%//  2     4     9     6


translationVector = unique(values, 'stable')
%//  3     2     1     4     5     9     6

然后我们想使用ismember 为任何给定的输入返回一个逻辑数组,以指定我们的平移向量的哪些值出现在输入参数中。

columns = ismember(translationVector, [3 2 4 9])
%//  1     1     0     1     0     1     0

然后我们只想在输出矩阵中设置这些列。

output(1, columns) = [3 2 4 9];

%//   3     2   NaN     4   NaN     9   NaN
%// NaN   NaN   NaN   NaN   NaN   NaN   NaN
%// NaN   NaN   NaN   NaN   NaN   NaN   NaN

然后我们对您的所有输入数组重复此操作。

实施

这里有一些代码可以做到这一点。

function [out, translationVector] = yourjoin(varargin)

    %// Make sure all inputs are row vectors
    varargin = cellfun(@(x)x(:).', varargin, 'uni', 0);   %'

    %// compute the translation vector
    translationVector = unique(cat(1, varargin{:}), 'stable');

    %// Pre-allocate your matrix of NaNs
    out = nan(numel(varargin), numel(translationVector));

    %// Fill in each row using each input argument
    for k = 1:numel(varargin)
        %// Identify columns that we have
        toreplace = ismember(translationVector, varargin{k});

        %// Set the values of those columns to the input values
        out(k,toreplace) = varargin{k};
    end
end

然后作为测试:

a = [3 2 4 9];
b = [3 1 5 9];
c = [2 4 9 6];

D = yourjoin(a,b,c)

     3     2   NaN     4   NaN     9   NaN
     3   NaN     1   NaN     5     9   NaN
   NaN     2   NaN     4   NaN     9     6

【讨论】:

  • 是的...在写作中ismember;好吧,我首先误解了这个问题,因为他把翻译向量写错​​了。
  • @Suever 可能会添加 transvec 作为第二个输出
  • @Dan 感谢您的推荐。已添加。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-11-11
  • 1970-01-01
  • 2021-12-04
  • 1970-01-01
  • 1970-01-01
  • 2010-10-21
  • 1970-01-01
相关资源
最近更新 更多