# How to check if each element of a matrix is larger/smaller than the mean of the elements of the respective line?

6 views (last 30 days)
João on 22 Nov 2022
Commented: João on 23 Nov 2022
I am still learning matlab basics and for that reason excuse any errors or "stupid" questions.
I have a square nxn matrix A and want to check if each element is larger than the mean of the respective line (for example, if the A11 element is larger than the mean of the elements from the first line). If that element is larger, replace it with "+". If it's smaller, replace it with "-". In the end I want to display the original matrix A and a different matrix B composed of "+" and "-".
This is everything I did, I know it's not correct but I tried a lot of different things and was unable to complete the task.
n=('Choose the size of the square matrix: ')
A=randi(n,n)
B=[];
for i=1:n
if mean(A(i,:)) > i
B(i)==B('+')
end
end
##### 2 CommentsShowHide 1 older comment
João on 23 Nov 2022
Thank you, this is what I was looking for. It works just as I needed it. I appreciate it!

DGM on 23 Nov 2022
Edited: DGM on 23 Nov 2022
Here's one way; I'm sure there are plenty of other ways.
% some matrix
A = magic(5)
A = 5×5
17 24 1 8 15 23 5 7 14 16 4 6 13 20 22 10 12 19 21 3 11 18 25 2 9
% row means
rmn = mean(A,2)
rmn = 5×1
13 13 13 13 13
% element is greater than row mean
isgtmean = A > rmn
isgtmean = 5×5 logical array
1 1 0 0 1 1 0 0 1 1 0 0 0 1 1 0 0 1 1 0 0 1 1 0 0
% generate B using a character map
charmap = '-+';
B = charmap(isgtmean+1)
B = 5×5 char array
'++--+' '+--++' '---++' '--++-' '-++--'
Of course, you haven't mentioned what should be done if an element is equal to the row mean. The above case prints '-' for cases where the element is less than or equal to the mean. If you want a third character, you could...
% some matrix
A = magic(5);
% note that array must be cast to numeric
rmn = mean(A,2);
indexmap = double(A == rmn);
indexmap(A > rmn) = 2
iseqmean = 5×5
2 2 0 0 2 2 0 0 2 2 0 0 1 2 2 0 0 2 2 0 0 2 2 0 0
% generate B using a character map
charmap = '-e+';
B = charmap(indexmap+1)
B = 5×5 char array
'++--+' '+--++' '--e++' '--++-' '-++--'
João on 23 Nov 2022
Thank you, I'll experiment with this. Appreciate it, I understood the logic behind it!

### Categories

Find more on Matrix Indexing in Help Center and File Exchange

R2021a

### Community Treasure Hunt

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

Start Hunting!