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

15 次查看(过去 30 天)
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 个评论
VBBV
VBBV 2022-11-23
编辑:VBBV 2022-11-23
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)
2 8 2 8 2 3 5 1 5 4 6 2 7 2 1 7 1 4 3 8 6 4 2 3 6 2 1 7 3 2 1 3 4 8 5 3 3 2 7 8 4 3 2 1 7 2 6 3 6 5 1 8 4 6 6 4 6 7 6 2 1 5 1 7 +-+-++-+ -+-+-++- +-+---++ -++-++++ +--+++-- -+++-+-+ --+-+--+ ---++-+-

请先登录,再进行评论。

回答(1 个)

DGM
DGM 2022-11-23
编辑:DGM 2022-11-23
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++' '--++-' '-++--'

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

产品


版本

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by