How to get the smallest value in submatrices

Hi,
I would appreciate if you could help me with this problem.
I have a big matrix , where are submatrices of the same size.
I want to get a vector containing the smallest elements in each submatrices. I want to avoid for loop as it might slow down my whole program.
Thanks.

 Réponse acceptée

B=randi(9,10,2)
B = 10×2
3 7 6 6 6 3 3 5 3 9 3 5 1 5 5 9 8 2 7 8
[m,n] = size(B);
k = 5;
if mod(m,k)
error('m must divisible by k');
end
minsub = min(reshape(B,[m/k k n]),[],[1 3]).'
minsub = 5×1
3 3 3 1 2

Plus de réponses (1)

cellfun(@min,B,'UniformOutput',false)
%or
cellfun(@min,cellfun(@min,B,'UniformOutput',false),'UniformOutput',false)

6 commentaires

Hung Dao
Hung Dao le 2 Oct 2021
Thanks, Kevin
I have to put the bis matrix B into a cell array first, right?
Yes, so something like this:
B = {rand(1,4);rand(3,5);rand(4,5);rand(9,1);rand(2,4)}
B = 5×1 cell array
{[0.5600 0.5471 0.0916 0.0913]} {3×5 double } {4×5 double } {9×1 double } {2×4 double }
cellfun(@min,B,'UniformOutput',false)
ans = 5×1 cell array
{[ 0.0913]} {[0.5940 0.2929 0.2503 0.0334 0.1946]} {[0.2727 0.1998 0.0695 0.0921 0.1135]} {[ 0.0420]} {[ 0.3392 0.4288 0.1739 0.4792]}
%or
cellfun(@min,cellfun(@min,B,'UniformOutput',false),'UniformOutput',false)
ans = 5×1 cell array
{[0.0913]} {[0.0334]} {[0.0695]} {[0.0420]} {[0.1739]}
This method allows you to find the minimum even if the submatrices where not the same size.
Hung Dao
Hung Dao le 2 Oct 2021
Wonderful !
Thank you very much.
I use cell arrays but did not realise that it can be such useful.
Hung Dao
Hung Dao le 2 Oct 2021
But, is there away to create this array without using for loop?
If I use a for loop to create this array then I could also just use forloop to find the minimum in each submatrices right?
I was under the impression that you already had a big matrix B that contained submatrices. If this is not the case, how are your data organized? Are all the matrices in a folder/workspace individually?
Hung Dao
Hung Dao le 2 Oct 2021
My apologies for the confusion.
My algorithm leads to a big matrix, not the submatrices.
But I need to partition the big matrix into submatrices of the same size, and in each submatrix I want to find the minimum value.
I hope it is clear now.
Thank you.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Startup and Shutdown dans Centre d'aide et File Exchange

Produits

Version

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by