Finding mean value over certain amount of values in a matrix
9 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Hello!
I would like to calculate the mean value of a defined number of values of the columns in a matrix.
e.g.
Mean value every 2 values column by column of A.
A = [1,2,3;4,6,8;7,12,7;14,4,23];
result = [2.5,4,5.5;10.5,8,15]
Thanks for the answers in advance.
0 commentaires
Réponses (4)
Arjun
le 22 Août 2024
Hi,
As per my understanding, you want to calculate the mean values of a column by considering 2 entries at a time.
To calculate the mean of every two values in each column of a matrix in MATLAB, you can reshape the matrix and then compute the mean along the desired dimension.
Kindly look at the code below to understand how to calculate mean of ever two values in a matrix:
% Define the matrix A
A = [1, 2, 3; 4, 6, 8; 7, 12, 7; 14, 4, 23];
% Number of rows to average over
blockSize = 2;
% Check if the number of rows is divisible by blockSize
if mod(size(A, 1), blockSize) ~= 0
error('The number of rows in A must be divisible by %d', blockSize);
end
% Reshape and compute the mean
result = mean(reshape(A, blockSize, [], size(A, 2)), 1);
% Remove the singleton dimension
result = squeeze(result);
% Display the result
disp(result);
There is one more alternate way using for loops which can be more intuitive.
Please refer to the code below:
% Define the matrix A
A = [1, 2, 3; 4, 6, 8; 7, 12, 7; 14, 4, 23];
% Number of rows to average over
blockSize = 2;
% Preallocate the result matrix
numBlocks = size(A, 1) / blockSize;
result = zeros(numBlocks, size(A, 2));
% Compute the mean for each block
for col = 1:size(A, 2)
for block = 1:numBlocks
% Calculate start and end indices for the block
startIdx = (block - 1) * blockSize + 1;
endIdx = block * blockSize;
% Compute the mean for the current block in the current column
result(block, col) = mean(A(startIdx:endIdx, col));
end
end
% Display the result
disp(result);
Here is a link for documentation of “mean” function used in the code above: https://www.mathworks.com/help/matlab/ref/mean.html
I hope it will help!
0 commentaires
Stephen23
le 22 Août 2024
Modifié(e) : Stephen23
le 22 Août 2024
Avoid SQUEEZE. More robust:
A = [1,2,3;4,6,8;7,12,7;14,4,23]
N = 2;
C = size(A,2);
B = reshape(mean(reshape(A,N,[],C),1),[],C)
B = [2.5,4,5.5;10.5,8,15]
Note that RESHAPE is very efficient as it does not move any data in memory
0 commentaires
Image Analyst
le 22 Août 2024
A = [1,2,3;4,6,8;7,12,7;14,4,23]
result = [2.5,4,5.5;10.5,8,15] % Your desired answer
r = conv2(A, [1;1]/2, 'valid');
r = r(1:2:end, :) % Take every other row of Convolution result so that it moves in "jumps"
Or you can use blockproc, the general purpose function meant for this operation. It's in the Image Processing Toolbox. See attached demos.
0 commentaires
Voir également
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!