How to call index of vector from matrix?

1 次查看(过去 30 天)
Hello, I have: n-by-3 matrix A, where xi,yi,zi are non-integer(e.g., x=-1.23;y=2.45;z=123.11):
A contain 10million element
A=[ x1 y1 z1 % element 1
x2 y2 z2 % element 2
x3 y3 z3 % element 3
x4 y4 z4 % element 4
.......
xn yn zn] % element n , where n=10,000,000
B=[ x3 y3 z3 % B contain 2 elements
x70 y70 z70]
Question: How to call index of matrix B from matrix A?(i don't wanna use "find(ismember(A,B,'rows'));" , since time consuming with large matrix A & B)
result=[3;70]
  1 个评论
Image Analyst
Image Analyst 2018-4-2
I don't know what "call index of matrix" or "call index of vector" means. Perhaps you can get a native English speaker to look it over. And what would you want? Would you want a 2-by-1 vector of rows where the numbers are found? Like output = [3; 70]? Or what??? Or do you want null/empty because row 3 followed by row 70 never ever appear in A?

请先登录,再进行评论。

回答(1 个)

Rik
Rik 2018-3-31
The code below executes in 0.35 seconds. This will scale about linearly with the number of rows in B.
%Generate data
A=rand(10000000,3);
B=A([3 70],:);
tic
%loop through B to find row indices
result=NaN(size(B,1),1);
for n=1:length(result)
true_row=...
A(:,1)==B(n,1) & ...
A(:,2)==B(n,2) & ...
A(:,3)==B(n,3);
row_idx=find(true_row);
if numel(row_idx)==0
%row not found, keep NaN
elseif numel(row_idx)>1
%more than 1 row found, throw warning
warning('no unique match for row')
%you can use the line below as well, if you just want to use the
%first row that matches.
%result(n)=row_idx(1);
else
result(n)=row_idx;
end
end
toc
  3 个评论
Rik
Rik 2018-4-2
Comparing many elements just is very time consuming. Use the profiler or tic and toc to figure out which method is fastest for you application. I don't think there are many ways to improve beyond ismember or the method I outline here. You might check to see if arrayfun or parfor yield any speedup.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

标签

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by