我遇到了匹配2个矩阵中元素的问题。可以使用ismember
匹配第一个元素,但第二个元素应该在一个范围内。请参阅以下示例:
% col1 is integerID, col2 is a number. -->col1 is Countrycode, col2 is date
bigmat = [ 600 2
600 4
800 1
800 5
900 1] ;
% col1 is integerID, col2 is VALUE, col2 is a range -->value is Exchange rate
datamat = {...
50 0.1 [2 3 4 5 6] % 2:6
50 0.2 [9 10 11] % 9:11
600 0.01 [1 2 3 4] % 1:4
600 0.2 [8 9 10] % 8:10
800 0.12 [1] % 1:1
800 0.13 [3 4] % 3:4
900 0.15 [1 2] } ; % 1:2
I need the answer as:
ansmat = [ 600 2 0.01
600 4 0.01
800 1 0.12
800 5 nan % even deleting this row is fine
930 1 0.15 ] ;
为简单起见:
bigmat是一个庞大的矩阵! 300,000-500,000行,因此可以理解矢量化代码。 datamat大约是5000行或更少。您可以将单元格转换为矩阵。对于每一行,我都有最小值和最大值。 3列是最小值:最大值。谢谢!
答案 0 :(得分:0)
以下是一种可能的实施方式:
%# data matrices
q = [
600 2
600 4
800 1
800 5
900 1
];
M = {
50 0.1 [2 3 4 5 6]
50 0.2 [9 10 11]
600 0.01 [1 2 3 4]
600 0.2 [8 9 10]
800 0.12 [1]
800 0.13 [3 4]
900 0.15 [1 2]
};
%# build matrix: ID,value,minDate,maxDate
M = [cell2num(M(:,1:2)) cellfun(@min,M(:,3)) cellfun(@max,M(:,3))];
%# preallocate result
R = zeros(size(M,1),3);
%# find matching rows
c = 1; %# counter
for i=1:size(q,1)
%# rows indices matching ID
ind = find( ismember(M(:,1),q(i,:)) );
%# out of those, keep only those where date number is in range
ind = ind( M(ind,3) <= q(i,2) & q(i,2) <= M(ind,4) );
%# check if any
num = numel(ind);
if num==0, continue, end
%# extract matching rows
R(c:c+num-1,:) = [M(ind,1) repmat(q(i,2),[num 1]) M(ind,2)];
c = c + num;
end
%# remove excess
R(c:end,:) = [];
预期的结果:
>> R
R =
600 2 0.01
600 4 0.01
800 1 0.12
900 1 0.15
答案 1 :(得分:-1)
我不完全确定我理解......第二个条目应该是'600 4 0.02'吗?
无论如何,您可以尝试以下方式:
% grab first column
col = bigmat(:, 1);
% find all entries in column that are equal to ID
rel = (col == id);
% retrieve just those rows
rows = bigmat(rel, :);
然后,一旦从矩阵中获得了所需的行,就可以将它们连接在一起,如下所示:
result = [rowsA(1:3) rowsB(2) rowsC(5:6)];