如果没有'使匹配和追加代码更有效率。环

时间:2014-08-01 07:57:57

标签: matlab

我试图将A的1 st 列与B的第1到第3个 rd 列相匹配,并附加相应的4 {/ 1}}到B列。

例如,

A

我比较A= 1 2 3 4 B= 1 2 4 5 4 1 2 3 5 3 1 1 1 1 2 3 4 5 6 5 A(:,1)

B(:, 1:3)1位于3

A(:,1)位于1的1 st ,2 nd ,3 rd 行中,因此追加B(:, 1:3)B([1 2 3], 4:end)'的1 st 行。 A位于3的2 nd 和4 th 行中,因此将B(:,1:3)追加到B([2 4], 4:end)'&# 39; s 2 nd 行。

这样就变成了:

A

我只能使用1 2 5 4 5 3 1 2 3 4 5 3 6 5 0 0 for进行编码。

if

我试图通过不使用clearvars AA A B mem mem2 mem3 A = [1 2 ; 3 4] B = [1 2 4 5 4; 1 2 3 5 3; 1 1 1 1 2; 3 4 5 6 5] for n=1:1:size(A,1) mem = ismember(B(:,[1:3]), A(n,1)); mem2 = mem(:,1) + mem(:,2) + mem(:,3); mem3 = find(mem2>0); AA{n,:} = horzcat( A(n,:), reshape(B(mem3,[4,5])',1,[]) ); %' end maxLength = max(cellfun(@(x)numel(x),AA)); out = cell2mat(cellfun(@(x)cat(2,x,zeros(1,maxLength-length(x))),AA,'UniformOutput',false)) for来提高此代码的效率,但无法找到答案。

2 个答案:

答案 0 :(得分:1)

试试这个

a = A(:,1);
b = B(:,1:3);
z = size(b);
b = repmat(b,[1,1,numel(a)]);
ab = repmat(permute(a,[2,3,1]),z);
row2 = mat2cell(permute(sum(ab==b,2),[3,1,2]),ones(1,numel(a)));
AA = cellfun(@(x)(reshape(B(x>0,4:end)',1,numel(B(x>0,4:end)))),row2,'UniformOutput',0);
maxLength = max(cellfun(@(x)numel(x),AA));
out = cat(2,A,cell2mat(cellfun(@(x)cat(2,x,zeros(1,maxLength-length(x))),AA,'UniformOutput',false)))

UPDATE 下面的代码几乎与迭代代码

同时运行
a = A(:,1);
b = B(:,1:3);
z = size(b);
b = repmat(b,[1,1,numel(a)]);
ab = repmat(permute(a,[2,3,1]),z);
df = permute(sum(ab==b,2),[3,1,2])';
AA = arrayfun(@(x)(B(df(:,x)>0,4:end)),1:size(df,2),'UniformOutput',0);
AA = arrayfun(@(x)(reshape(AA{1,x}',1,numel(AA{1,x}))),1:size(AA,2),'UniformOutput',0);    
maxLength = max(arrayfun(@(x)(numel(AA{1,x})),1:size(AA,2)));
out2 = cell2mat(arrayfun(@(x,i)((cat(2,A(i,:),AA{1,x},zeros(1,maxLength-length(AA{1,x}))))),1:numel(AA),1:size(A,1),'UniformOutput',0));

答案 1 :(得分:1)

这个怎么样:

%# example data
A = [1 2
     3 4];

B = [1 2 4 5 4
     1 2 3 5 3
     1 1 1 1 2
     3 4 5 6 5];

%# rename for clarity & reshape for algorithm's convenience
needle   = permute(A(:,1), [2 3 1]);
haystack = B(:,1:3);
data     = B(:,4:end).';

%# Get the relevant rows of 'haystack' for each entry in 'needle'
inds = any(bsxfun(@eq, haystack, needle), 2);

%# Create data that should be appended to A
%# All data and functionality in this loop is local and static, so speed 
%# should be optimal.
append = zeros( size(A,1), numel(data) );
for ii = 1:size(inds,3)    
    newrow = data(:,inds(:,:,ii));
    append(ii,1:numel(newrow)) = newrow(:);    
end

%# Now append to A, stripping unneeded zeros
A = [A append(:, ~all(append==0,1))]