Gul*_*zar 0 matlab join vector
我试着查看,但不知道该找什么...
我需要"表连接"N个向量,意思是,创建一个矩阵,其中每个输入向量都有一行,每个可能的条目都有一列.
还有一个翻译向量可以轻松访问哪个列负责哪个条目
例如
a = [3, 2, 4, 9]
b = [3, 1, 5, 9]
c = [2, 4, 9, 6]
Run Code Online (Sandbox Code Playgroud)
然后
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,
]
Run Code Online (Sandbox Code Playgroud)
用翻译矢量
[3,2,1,4,5,9,6]
Run Code Online (Sandbox Code Playgroud)
所以如果我找到关于第i列的内容,我可以很容易地知道该列代表什么.
我更喜欢连接操作能够接收n个向量(它们可以具有相同的长度),但是2也可以.
此外,第二眼,这些数据表示在某些方面似乎有点多余.也许有一种更好的方式来表示"连接矩阵"
谢谢
基本上,您希望按照接收顺序使用所有可能的唯一输入构建您的翻译向量.为此,我们可以将所有输入连接在一起,而不是找到唯一值.
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
Run Code Online (Sandbox Code Playgroud)
然后我们想要ismember用于为任何给定输入返回逻辑数组,以指定我们的转换向量的哪些值存在于输入参数中.
columns = ismember(translationVector, [3 2 4 9])
%// 1 1 0 1 0 1 0
Run Code Online (Sandbox Code Playgroud)
然后,我们想要在输出矩阵中设置这些列.
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
Run Code Online (Sandbox Code Playgroud)
然后,我们对所有输入数组重复此操作.
这是一些完成它的代码.
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
Run Code Online (Sandbox Code Playgroud)
然后作为测试:
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
Run Code Online (Sandbox Code Playgroud)