perform an action on part of a column in a matrix

2 次查看(过去 30 天)
Hello
I have a matrix of 3 columns:
The first column contains some numbers that I want to average
Second, either 1 or 0.
3rd is empty because I want to insert values to this column
for example:
5 0 0
4 0 0
6 0 0
4 1 0
7 0 0
8 0 0
9 0 0
7 1 0
1 0 0
4 0 0
3 0 0
What I need is to define a range according to the second column (from the first to the last zero)
calculate the average of the numbers in these rows in column 1
copy the average to column 4
For example:
the average of 5,4,6 is 5
and the average of 4, 7, 8, 9 is 7
so it should look like this:
5 0 5
4 0 5
6 0 5
7 1 7
8 0 7
9 0 7
My questions are:
1. How can I define such range (from zero to zero without 1)?
2. How can I insert the calculated value (the average) into every corresponding row?
Thank you so much for your help!

回答(1 个)

goerk
goerk 2016-3-30
M %your matrix
maskData = cumsum(M(:,2));
for i=0:max(maskData)
mask = maskData==i;
meanValue = mean(M(mask,1));
M(mask,3) = meanValue;
end

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by