How to select specific values from a matrix?
5 次查看(过去 30 天)
显示 更早的评论
I have a matrix which looks like this -
val =
[
1, a, b, c;
1, c, d, e;
1, a, b, d;
2, e, d, c;
2, r, t, v;
3, e, t, z;
3, r, t, x;
3, d, e, v;
3, r, d, f;
4, f, d, x;
1, r, t, c;
2, r, x, t;
4, a, d, x;
]
it may have varying numbers of rows. The first column contains the identifier that I want to use to sort the data such that all the columns with the index 1, or 2, or 3, or 4 are in one separate matrix. So for the example above, I should be able to create 4 matrix with the rows for the values from the three columns in that specific index.
So the output will be -
val_index1 =
[
1, a, b, c;
1, c, d, e;
1, a, b, d;
1, r, t, c;
]
val_index2 =
[
2, e, d, c;
2, r, t, v;
2, r, x, t;
]
val_index3 =
[
3, e, t, z;
3, r, t, x;
3, d, e, v;
3, r, d, f;
]
val_index4 =
[
4, f, d, x;
4, a, d, x;
]
How can I do this?
many thanks for your suggestion, Vijoya
0 个评论
回答(1 个)
Azzi Abdelmalek
2014-12-22
编辑:Azzi Abdelmalek
2014-12-22
%Example
a=[1;1;1;2;2;3;3;3;3;4;1;2;4]
b=randi(9,numel(a),3)
c=[a b];
%------------------The code----------------
y=accumarray(a,1:numel(a),[],@(x) {c(x,:)})
celldisp(y)
You don't need to create a variable for each sub-matrix. You can get the four matrices:
y{1}
y{2}
y{3}
y{4}
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Shifting and Sorting Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!