How to extract rows based on column values in a matrix?

125 ビュー (過去 30 日間)
qualiaMachine
qualiaMachine 2015 年 6 月 22 日
コメント済み: Abdelrahman Mohamed 2022 年 11 月 24 日
I am working with data that is in a 152867x2 matrix. The first column contains one of three values ranging from 1-3. The second column, however, has a unique value for each row (see example data below). I would like to know how I can write a program that can extract 3 matrices according to the value of the first column (see example output). I'm new to MATLAB, so explicit instructions would be fantastic. Thanks.
Example Data
3, 0.1234
1, 0.1345
1, 0.1456
2, 0.1567
1, 0.1678
1, 0.1789
Desired Output - Three Matrices
1) 3, 0.1234
2) 2, 0.1567
3) 1, 0.1345
1, 0.1456
1, 0.1678
1, 0.1789
  2 件のコメント
Kevin Maakomane
Kevin Maakomane 2022 年 8 月 19 日
extract=data(row_nu,:)
or
tranpose data using ' operator and extract column wise
baby
baby 2022 年 9 月 20 日
great, thank you, works for me as well.

サインインしてコメントする。

採用された回答

Mukul Rao
Mukul Rao 2015 年 6 月 23 日
編集済み: Mukul Rao 2015 年 6 月 24 日
Here are links to a few concepts that would be useful for performing such operations:
1. Matrix Indexing : Using Logicals in Array Indexing
2. Find array elements based on a specified condition
Finally, here is an example on how you can implement these concepts. There are many ways to do this, here is one such method.
%Example matrix
A = [3, 0.1234
1, 0.1345
1, 0.1456
2, 0.1567
1, 0.1678
1, 0.1789];
%Find indices to elements in first column of A that satisfy the equality
ind1 = A(:,1) == 1;
ind2 = A(:,1) == 2;
ind3 = A(:,1) == 3;
%Use the logical indices to index into A to return required sub-matrices
A1 = A(ind1,:);
A2 = A(ind2,:);
A3 = A(ind3,:);
  5 件のコメント
Herbert Nyakoojo
Herbert Nyakoojo 2020 年 8 月 15 日
Thank you people
Abdelrahman Mohamed
Abdelrahman Mohamed 2022 年 11 月 24 日
Thanks you Mukul Rao its working

サインインしてコメントする。

その他の回答 (1 件)

Steven Lord
Steven Lord 2020 年 11 月 26 日
This wasn't an option when the question was asked originally but depending what you're trying to do with those "3 matrices", using some of the functions in the 'Grouping and Binning Data' section on this documentation page may be useful. For example, to compute the mean of values in the second column that have the same value in the first column:
A = [3, 0.1234;
1, 0.1345;
1, 0.1456;
2, 0.1567;
1, 0.1678;
1, 0.1789];
G = groupsummary(A, A(:, 1), @mean)
G = 3×2
1.0000 0.1567 2.0000 0.1567 3.0000 0.1234

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by