Binning matrix data (negative and positive decimals): mean of each 100 rows and create a new matrix
4 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
William Norbey Sanchez Luna
le 26 Août 2024
Commenté : William Norbey Sanchez Luna
le 29 Août 2024
I have a A= 7382300X12 matrix. I want to reduce it by averaging every 1000 rows in all columns. So at the end I will have a B= 73823X12 matrix.
The matrix A have negative and positive decimals, so blockproc() didn't work for me.
How can I do it?
2 commentaires
Walter Roberson
le 26 Août 2024
You have the small issue that 7382300 is not evenly divisible by 1000. Should the final 300 entries be treated as a complete group?
Réponse acceptée
Sahas
le 27 Août 2024
As per my understanding, you would like to reduce the size of an input matrix by taking the mean of every 1000 rows and all the columns.
The following code snippet achieves the desired functionality. You can modify the input matrix to suit your preferred data types.
inputMatrix = randi([-100, 100], 3300, 12);
numRows = size(inputMatrix, 1);
numCols = size(inputMatrix, 2);
blockSize = 1000;
% Calculate the number of complete blocks
numBlocks = floor(numRows / blockSize);
% Reshape inputMatrix to group every 'blockSize' rows together for each column
reshapedA = reshape(inputMatrix(1:blockSize*numBlocks, :), blockSize, numBlocks, numCols);
% Calculate the mean along the first dimension
semiFinalMatrix = squeeze(mean(reshapedA, 1))
% Assuming treating the leftover rows as one group and getting their mean as well
remainingRows = mod(numRows, blockSize);
if remainingRows > 0
% Calculate the mean of the remaining rows
remainingMean = mean(inputMatrix(end-remainingRows+1:end, :), 1);
% Append the mean of the remaining rows to semiFinalMatrix
finalMatrix = [semiFinalMatrix; remainingMean]
end
Refer to the following MathWorks documentation links for more information on “reshape” and “squeeze” functions.
- https://www.mathworks.com/help/matlab/ref/reshape.html
- https://www.mathworks.com/help/matlab/ref/squeeze.html
Hope this is beneficial!
Voir également
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!