Finding mean value over certain amount of values in a matrix
조회 수: 9 (최근 30일)
이전 댓글 표시
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
답변 (4개)
Arjun
2024년 8월 22일
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
Image Analyst
2024년 8월 22일
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
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!