How to check if each element of a matrix is larger/smaller than the mean of the elements of the respective line?
15 views (last 30 days)
Show older comments
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 Comments
VBBV
on 23 Nov 2022
Edited: VBBV
on 23 Nov 2022
This is one way ,you can extend the same logic a bit further as below
n = 8; % assume input size of matrix
A = randi(n,n);
B = char(zeros(size(A))); % preallocate matrix size, B of char data type
for i=1:n
for j = 1:n
if mean(A(i,:)) > A(i,j)
B(i,j)= '+';
else
B(i,j) = '-';
end
end
end
disp(A), disp(B)
Answers (1)
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)
% row means
rmn = mean(A,2)
% element is greater than row mean
isgtmean = A > rmn
% generate B using a character map
charmap = '-+';
B = charmap(isgtmean+1)
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
% generate B using a character map
charmap = '-e+';
B = charmap(indexmap+1)
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!