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 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