How do I find averages of certain values in a matrix.

Hi all!
So basically I have a 76x76 matrix, but I want to find the average for the values for the corresponding pairs, e.g. 1x2 and 2x1, 22x37 and 37x22, 6x58 and 58x6 etc, from 1x2 and 2x1 all the way to 75x76 and 76x75 (excluding repeated numbers like 1x1). Is there a way for me to do this and put it into like a table?
Thank you!

2 Comments

What is the size of the expected result?
Lakyn
Lakyn on 22 Aug 2016
Edited: Lakyn on 22 Aug 2016
It will be 1+2+3...+75, so 2850!

Sign in to comment.

 Accepted Answer

What does 22x37 denote here? Is that YourMatrix(22,37) Or is it all sub-matrices that are 22 rows and 37 columns?
Guessing on what you want:
triu( (YourMatrix + YourMatrix.') / 2, 1)

6 Comments

oh 22x37 is just an example, the number that belongs to the 22nd row and 37th column.
May I know what does the triu at the front stand for? Thanks!
triu is upper triangle.
See also diag(). And if you happen to have the stats toolbox, then you could also extract data using squareform(), if you zero the diagonal first.
ah thank you. my matrix is not a square matrix though, as in my 1x2 and my 2x1 values are different. So isn't taking only the upper triangle wrong in this case?
One way:
temp = (YourMatrix + YourMatrix.') / 2;
temp(1:size(YourMatrix,1)+1:end) = 0; %zero the diagonal of the result
output_vector = squareform(temp);
Another way:
temp = (YourMatrix + YourMatrix.') / 2;
mask = triu( ones(size(temp)), 1 );
output_vector = temp(mask);
Another way:
nrow = size(YourMatrix, 1);
temp = (YourMatrix + YourMatrix.') / 2;
output_cell = cell(nrow-1, 1);
for K = 1 : nrow - 1
output_cell{K} = diag(temp, K);
end
Depends what output order and format you want the results in.
Hi,
oh wow thanks so much! I just tried them all. I couldn't get the second one to run though, it says there an error in the last line (output_vector = temp(mask);).
Also, I don't really understand the output of the third way, it doesn't really give any results!
temp = (YourMatrix + YourMatrix.') / 2;
mask = triu( true(size(temp)), 1 );
output_vector = temp(mask);
The last of them produces a cell array output; see http://www.mathworks.com/help/matlab/cell-arrays.html
output_cell{1} is the first diagonal as a vector, output_cell{2} is the second diagonal as a vector, and so on. The diagonals are the pairs whose indices add up to the same value -- so for example T(2,75), T(3,74), T(4,73), T(5,72) and so on. You have not really said what you want the table to look like.

Sign in to comment.

More Answers (0)

Categories

Community Treasure Hunt

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

Start Hunting!