How to align multiple tables/matrices based on the first column
古いコメントを表示
Hello,
I am new to programming, and trying to write a script to align multiple 4-column tables based on the first column. The first column are numbers in the order from small to large(you may think it as date). The numbers may be slightly different from table to table, and some tables may have more rows than the others. In the script I wrote below, it covers 4 tables(A,B,C,D), and generate the aligned table A. I can repeat the codes to generated aligned table B, C, D as well. However, my problem is that the number of input tables may vary from 4 to 20, and I don't want to revise my script every time. I have not figured out how to write such a script. Any suggestions are appreciated.
The script is the following:
function z=align4(A, B, C, D, reslst) % align matrices A, B, C and D
if nargin<5, reslst=[]; end %default: all resid.
if isempty(reslst),
rlst=[min([A(:,1);B(:,1);C(:,1);D(:,1)]):max([A(:,1);B(:,1);C(:,1);D(:,1)])]'; % Generate a complete residue list.
else
rlst=reslst(:);
end
nres=length(rlst);
z=NaN*ones(nres,4);
z(:,1)=rlst;
for ii=1:nres,
indA=find(A(:,1)==rlst(ii));
if ~isempty(indA), z(ii,2:end)=A(indA,2:end); end
end
return
2 件のコメント
Walter Roberson
2011 年 9 月 30 日
You have not defined what you mean by "align" for this purpose.
Do you mean something like a database "join" operation ? http://en.wikipedia.org/wiki/Join_%28SQL%29
DZ
2011 年 9 月 30 日
採用された回答
その他の回答 (1 件)
Oleg Komarov
2011 年 9 月 30 日
function z = align4(reslst,varargin) % align matrices A, B, C and D
if isempty(reslst)
rlst = [min(cellfun(@(x) x(1,1),varargin)):max(cellfun(@(x) x(end,1),varargin))].';
else
rlst = reslst(:);
end
nList = numel(rlst);
nIn = numel(varargin);
z = cell(nIn,1);
for n = 1:nIn
z{n} = NaN(nList,size(varargin{n},2));
z{n}(ismember(rlst,varargin{n}(:,1)),:) = varargin{n};
end
An example:
t1 = [[2; 4; 6] randi(100,3,4)];
t2 = [[5; 7] randi(100,2,4)];
align4([],t1,t2)
カテゴリ
ヘルプ センター および File Exchange で Matrices and Arrays についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!