How extract specific data from a large matrix and save in new matrix?
1 view (last 30 days)
Show older comments
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
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?
Accepted Answer
More Answers (1)
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
on 31 Jan 2017
Edited: the cyclist
on 31 Jan 2017
Oops! I accidentally swapped the argument order in ismember. Andrei got it right.
See Also
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!