MATLAB: How to find a value in x axis in 1d plot with a given y

1d arrayplotplotting

Hi,
I have a 1D array(named "rms") with rms(root mean square) values in a single row arranged by time slots in column id. I need to find a point in the time slot when the maximum rms value was exactly half.For example, I found out maximum rms using : maxRMS = max(rms); Now I know that there won't be an exact value in the array as they are all rms values. If I plot them using plot(rms), I get a curve and I wish to find that x axis value in the curve when the rms was exactly half.

Best Answer

Try this:
clc; % Clear the command window.
close all; % Close all figures (except those of imtool.)
clear; % Erase all existing variables. Or clearvars if you want.
workspace; % Make sure the workspace panel is showing.
format long g;
format compact;
fontSize = 20;
% Create sample data.
y = [0.0000 0.0000 0.0000 0.0001 0.0001 0.0002 0.0003 0.0003 0.0004 0.0005 0.0006 0.0007 0.0008 0.0009,...
0.0010 0.0011 0.0012 0.0014 0.0020 0.0030 0.0039 0.0061 0.0109 0.0220 0.0456 0.1540 0.3423 0.5535,...
0.6578];
x = 1 : length(y);
plot(x, y, 'b.-', 'LineWidth', 2, 'MarkerSize', 25);
grid on;
% Enlarge figure to full screen.
set(gcf, 'Units', 'Normalized', 'OuterPosition', [0, 0.04, 1, 0.96]);
% Get the rms value of y
yRms = rms(y)
% Get the max value of y and the index where it occurs.
[yMax, indexOfMax] = max(y)
% Put a line there

hold on;
line([x(indexOfMax), x(indexOfMax)], ylim, 'Color', 'r', 'LineWidth', 2);
% Find the half max
halfMax = yMax / 2
% Put a line there
line(xlim, [halfMax, halfMax], ylim, 'Color', 'r', 'LineWidth', 2);
% Find two y points on the left side.
for k = indexOfMax : -1 : 1
if y(k) < halfMax
index1 = k;
index2 = k + 1;
plot([x(index1), x(index2)], [y(index1), y(index2)], 'ro', 'LineWidth', 2, 'MarkerSize', 20);
break
end
end
% Find the point where y = halfMax more exactly.
coefficients = polyfit([x(index1), x(index2)], [y(index1), y(index2)], 1);
% Get the x value by setting y = halfMax
% y = coefficients(1) * x + coefficients(2)
% So x at halfMax = (halfMax - coefficients(2)) / coefficients(1)
xAtHalfMax = (halfMax - coefficients(2)) / coefficients(1)
% Plot a line there
line([xAtHalfMax, xAtHalfMax], ylim, 'Color', 'm', 'LineWidth', 2, 'MarkerSize', 50);
% Plot a cursor there
plot(xAtHalfMax, halfMax, 'm*', 'LineWidth', 2, 'MarkerSize', 50);
message = sprintf('HalfMax at (%.3f, %.3f)', xAtHalfMax, halfMax);
title(message, 'fontSize', fontSize);
fprintf('%s\n', message);
uiwait(helpdlg(message));