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
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)
回答(1 个)
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)
% 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)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!