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

조회 수: 13 (최근 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 +-+-++-+ -+-+-++- +-+---++ -++-++++ +--+++-- -+++-+-+ --+-+--+ ---++-+-
João
João 2022년 11월 23일
Thank you, this is what I was looking for. It works just as I needed it. I appreciate it!

댓글을 달려면 로그인하십시오.

답변 (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