- Understand the Data Structure: Since you have a vector A where each two elements correspond to a group, you can reshape the vector into a matrix where each column represents a group.
- Calculate the Average: Use the mean function to compute the average of each row, which corresponds to the (i)-th element across all groups.
Average of two elements in a vector that have specific index
7 views (last 30 days)
Show older comments
Hi all,
I have a vector
where each two elements corresponds to a group, so as a result there are four goups and in each there are two numbers, as shown below in the image:

I want to compute the averge of ith-element of each group and store the answer in a new vector. For example, the averge of the first element from each gorup (the red circles) is 4, as shwon above. The resulting vector should be
in size.
%Define the number of elements in each group
NoElements = 2;
%Define the number of groups
NoGroups = 4;
%Define the vector
A =[1
2
3
4
5
6
7
8];
%perform the averaging
for j = 1:NoElements
A_ave(j) = ?
end
Any help would be appreicted.
0 Comments
Accepted Answer
Shivam
on 18 Feb 2025
Hi,
To compute the average of the (i)-th element from each group and store the result in a new vector, you can follow these steps in MATLAB. Here's how you can do it:
Here's the MATLAB code to achieve this:
% Define the number of elements in each group
NoElements = 2;
% Define the number of groups
NoGroups = 4;
% Define the vector
A = [1; 2; 3; 4; 5; 6; 7; 8];
% Reshape the vector into a matrix where each column represents a group
A_matrix = reshape(A, NoElements, NoGroups);
% Perform the averaging
A_ave = mean(A_matrix, 2);
% Display the result
disp('Averaged vector:');
disp(A_ave);
Hope it helps.
0 Comments
More Answers (0)
See Also
Categories
Find more on Resizing and Reshaping Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!