Select certain percentage of a plot
Show older comments
Hi all,
I was wondering, how can I select certain points which contains a % desired amount.
To make it a bit clearer, imagine a x,y plot where
x = [ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20]
y = [0 1 3 1 2 0 0 0 2 1 2 2 4 5 6 7 8 9 11 20]
I want to find that point where y reaches for example 10% of the sum of y (which should be about 8.4 in this case). This should be between x = 8 and x = 9.
How can I give Matlab a command to find it for a certain percentage and the value of the x-axis? And is it also possible to indicate the value in the plot itself?
Thanks in forward
Accepted Answer
More Answers (1)
aara
on 11 Feb 2019
You can use a for loop add all the totals together incrementally and check when its above your desired value:
x = 1:20;
y = [0 1 3 1 2 0 0 0 2 1 2 2 4 5 6 7 8 9 11 20];
total = 0;
percent = 10; %set percentage.
for i=1:length(y)
total = sum(y(1:i)); %this adds more y values together with each iteration
if total > sum(y)*percent/100
disp(x(i)) %x is only displayed when the sum values of y are bigger than percentage of y
break
end
end
Or if you need to integrate for area under the curve then:
You can use the trapz function in matlab (this gives different results) :
x = 1:20;
y = [0 1 3 1 2 0 0 0 2 1 2 2 4 5 6 7 8 9 11 20];
total = 0; %this is to add the total area under the curve
percent = 10;
for i=1:length(y)
total = total+trapz(y(1:i)); %with each iteration, the integration area increases
if total >= sum(y)*percent/100 %if the area under the curve passes your required percent then it would display corresponding x value and stop the loop.
disp("X-value: "+ x(i))
break
end
end
Categories
Find more on Numerical Integration and Differentiation 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!