Classify rows of a matrix

6 ビュー (過去 30 日間)
Pooneh Shah Malekpoor
Pooneh Shah Malekpoor 2021 年 3 月 16 日
コメント済み: the cyclist 2021 年 3 月 16 日
Hello
I want to know how it is possible to define a condition as if the numbers at the second column of some rows of a matrix are equal to each other and at the same time if the numbers at the third column of the same rows are equal to each other , then classify the first column numbers of those rows and calculate their mean values...in simple words, consider matrix A as:
A=[0.9 20.1 0.3;
0.8 19 1;
0.57 20.1 0.3;
0.7 20.1 0.4;
1 19 1]
I need a code to calculate the mean value of 0.9 and 0.57 as the numbers in second and third column of row 1 and 3 are the same. It should also calculate the mean of 0.8 and 1 as the numbers in second and third column of row 2 and 5 are the same.
Any help is highly appriciated.
Bests

採用された回答

the cyclist
the cyclist 2021 年 3 月 16 日
A=[0.9 20.1 0.3;
0.8 19 1;
0.57 20.1 0.3;
0.7 20.1 0.4;
1 19 1]
A = 5×3
0.9000 20.1000 0.3000 0.8000 19.0000 1.0000 0.5700 20.1000 0.3000 0.7000 20.1000 0.4000 1.0000 19.0000 1.0000
[uniqueA23, ~, subs] = unique(A(:, [2 3]), 'rows');
meanA1 = accumarray(subs, A(:,1), [], @mean);
output = [meanA1, uniqueA23]
output = 3×3
0.9000 19.0000 1.0000 0.7350 20.1000 0.3000 0.7000 20.1000 0.4000
  2 件のコメント
Pooneh Shah Malekpoor
Pooneh Shah Malekpoor 2021 年 3 月 16 日
Thank you so much. Could you please just explain a bit about it? I am not that professional!
the cyclist
the cyclist 2021 年 3 月 16 日
Sure, but you'll probably need to read and understand some of the documentation of unique() and accumarray() to get a complete understanding.
The first line is identifying the rows of A where columns 2 and 3 are the same. The input
A(:, [2 3])
is all rows of A, but only the 2nd and 3rd column. The input 'rows' indicates that we want the unique rows, not the unique elements.
The output
uniqueA23
is the those unique rows. The output
subs
keeps track of which rows in the original matrix correspond to the unique ones.
The second line uses the powerful accumarray function -- "accumulate array". In this case, "accumulate" means "take groups of rows -- defined by subs -- and perform an operation on them". In this case, the input is the first column of A, and we have defined that operation to be the mean.

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

その他の回答 (0 件)

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by