MATLAB Answers

How to call index of vector from matrix?

6 views (last 30 days)
ha ha
ha ha on 31 Mar 2018
Commented: ha ha on 3 Apr 2018
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 Comment
Image Analyst
Image Analyst on 2 Apr 2018
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?

Sign in to comment.

Answers (1)

Rik
Rik on 31 Mar 2018
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 Comments
ha ha
ha ha on 3 Apr 2018
@Rik Wisselink. Thank so much

Sign in to comment.

Tags

Community Treasure Hunt

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

Start Hunting!