Manipulation of matrices and vectors without using loops
2 次查看(过去 30 天)
显示 更早的评论
Five problems. Please, check solutions.
1. Let M be a matrix with dimensions m x n. Calculate the sum of all elements greater then mean value of the whole matrix (without using loop).
My solution:
sum(M(M>mean(M,'all')))
2. Let M be a matrix with dimensions m x n. Calculate the number of all elements in the matrix which differ less then 1 from the whole matrix mean value (without using loop).
My solution:
sum(mean(M,'all')<1)
3. Let M be a matrix with dimensions m x n. Delete all columns for which their mean value is closer to their minimum value then those which are closer to maximum value (without using loop).
My solution:
M(mean(M)-min(M)<mean(M)-max(M))=[]
4. Let W be a vector. Calculate how many elements in a vector with odd indices are greater then mean value (without using loop).
My solution: (this is surely not correct)
numel(mod(find(W),2)==0 & find(W(W>mean(W))))
5. Let W be a vector. Calculate how many elements won't change their position after ascending sorting (without using loop).
My solution:
nnz(find(sort(W))==find(W))
0 个评论
回答(1 个)
Jan
2018-9-19
编辑:Jan
2018-9-19
I suggest to test these codes by your own at first.
"differ less then 1 from the whole matrix mean"
sum(mean(M,'all')<1)
"Differ" cries for using a minus operation.
M(mean(M)-min(M)<mean(M)-max(M))=[]
The mean value is greater than the minimum and smaller than the maximum. Therefore mean(M)-min(M) is positive, while mean(M)-max(M) is negative. In consequence mean(M)-min(M)<mean(M)-max(M) cannot be true.
Consider the 2nd dimension also (see Adam's comment).
numel(mod(find(W),2)==0 & find(W(W>mean(W))))
The find commands are not meaningful here. Remember that find(W) replies the indices of the non-zero elements.
Calculate how many elements in a vector with odd indices are greater then mean value
elements with odd indices: W(1:2:end)
mean value: mean(W)
together: sum(W(1:2:end) > mean(W))
And the last one:
nnz(find(sort(W))==find(W))
The find commands are not useful again. Omit them.
[EDITED] See Steven Lord's comment: The older mean(A(:)) is accepted as mean(A, 'all') since R2018b.
2 个评论
Steven Lord
2018-9-19
Fails: There is no 'all' flag for mean.
Adam
2018-9-19
Ah yes, I was meaning to upgrade to R2018b!
Another reason why making it compulsory for users to include the release in a question, but that is a different matter! In this case the user must be using the very latest version while myself and Jan haven't caught up with that yet. Usually the problem is with people using older versions without us realising :)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Operators and Elementary Operations 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!