Clear Filters
Clear Filters

How extract specific data from a large matrix and save in new matrix?

3 views (last 30 days)
Hi, I have a matrix say"mv" ( 45x1) and another matrix called "a" (a=15252x23). Every value of 'mv' is present in 'a' (first column of a), so i want a new matrix say "b" where the data of only mv id should be there and rest should be omitted. I am writing code but unable to get desired answer. Below is the code. Please help.
for i = 1:length (mv);
if a (:,1) == mv;
mv_ramp (i,:) = a(a(:,1)== mv(i),:); % mv_ramp is new matrix where extracted data should be stored
end;
end;
Output: Matrix dimensions must agree (Error is coming). And Only one vehicle id data is stored in mv_ramp. Please identify my mistake. Thanks
  2 Comments
the cyclist
the cyclist on 31 Jan 2017
Is each value of in mv guaranteed to be in a(:,1) exactly once, or could it be duplicated? If the latter, then you are trying to copy several rows into one.
Also, are you sure that each values of mv is exactly equal to the values in a(:,1), or could they possibly be different by tiny, floating-point error?
Yasir Ali
Yasir Ali on 31 Jan 2017
Actually, mv is obtained using "unique" command and there are multiple value of mv in 'a'. Yes i am trying to copy all rows of same id from mv but getting issue. I think this might help you to understand my problem. Thanks

Sign in to comment.

Accepted Answer

Andrei Bobrov
Andrei Bobrov on 31 Jan 2017
mv_ramp = a(ismember(a(:,1),mv),:);

More Answers (1)

the cyclist
the cyclist on 31 Jan 2017
Edited: the cyclist on 31 Jan 2017
If you are guaranteed that the value of mv is in a(:,1), then you actually do not need the if statement.
This simple version worked for me:
mv = [3 2 1]';
a = [2 16;
1 17;
3 18];
for i = 1:length(mv)
mv_ramp (i,:) = a(a(:,1)== mv(i),:);
end
This could also have been vectorized as follows:
[~,loc] = ismember(mv,a(:,1));
mv_ramp = a(loc,:)
  3 Comments
the cyclist
the cyclist on 31 Jan 2017
Edited: the cyclist on 31 Jan 2017
Oops! I accidentally swapped the argument order in ismember. Andrei got it right.

Sign in to comment.

Categories

Find more on Numeric Types in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!