Extracting rows from a matrix based on values in columns

1 回表示 (過去 30 日間)
Nathan Paul
Nathan Paul 2016 年 5 月 8 日
コメント済み: Stephen23 2017 年 10 月 16 日
Following on from this question
I have a large number of conditions lets say i needed 28 different values in the columns to find, how would i do that without finding the indices in 28 different lines, not sure how to do the for loop? :/

回答 (1 件)

Stephen23
Stephen23 2016 年 5 月 8 日
編集済み: Stephen23 2016 年 5 月 8 日
This is easy using accumarray:
A = [3, 0.1234;
1, 0.1345;
1, 0.1456;
2, 0.1567;
1, 0.1678;
1, 0.1789];
C = accumarray(A(:,1),A(:,2),[],@(n){n});
Which places each collection into one cell of cell array C:
>> C
C =
[4x1 double]
[ 0.1567]
[ 0.1234]
>> C{1}
ans =
0.1345
0.1456
0.1678
0.1789
This will automatically create as many cells as needed in one output variable C. You need to use cell array indexing to access the contents of the cells of C. Note that you should not attempt to create 28 separate variables and access them dynamically in a loop: this is very poor programming practice (sadly much loved by beginners, who think it is great) that is slow, buggy, and obfuscated:
  2 件のコメント
Maria445
Maria445 2017 年 10 月 8 日
What if I have more than 1 column? That is, I want A to be a 6-by-4 matrix for example, so to have C{1} = 4-by-3 matrix?
Stephen23
Stephen23 2017 年 10 月 16 日
@Maria445: make the second input to accumarray the row indices, and change the anonymous function to use those indices to extract the required rows:
>> R = 1:size(A,1);
>> C = accumarray(A(:,1),R.',[],@(r){A(r,:)})

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

カテゴリ

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

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by