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

1 次查看(过去 30 天)
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 个评论
the cyclist
the cyclist 2017-1-31
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 2017-1-31
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

请先登录,再进行评论。

采纳的回答

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

更多回答(1 个)

the cyclist
the cyclist 2017-1-31
编辑:the cyclist 2017-1-31
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 个评论
the cyclist
the cyclist 2017-1-31
编辑:the cyclist 2017-1-31
Oops! I accidentally swapped the argument order in ismember. Andrei got it right.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Numeric Types 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by