MATLAB: How to convert sine signal into rms signal, using mfile

electrical engineering matlab

I have a sinus fault signal. I need rms signal to relay can work

Best Answer

The RMS function in the Signal Processing Toolbox will give you the RMS value of your entire signal. If you need the RMS within a sliding window, then see this code below and adapt parameters as needed:
% Initialization steps.
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;
% Setup: create the signal.
x = linspace(-100, 100, 800); % 800 points from -100 to +100
% Define the period of the sine wave, and it's amplitude
period = 40;
amplitude = 15;
phase = 5;
% Create the signal
y = amplitude * sin(2 * pi * x / period + phase);
subplot(2, 1, 1);
plot(x, y, 'b-', 'LineWidth', 2);
title('Original Signal', 'FontSize', fontSize);
ylabel('y', 'FontSize', fontSize);
xlabel('x', 'FontSize', fontSize);
grid on;
ax = gca;
ax.XAxisLocation = 'origin';
ax.YAxisLocation = 'origin';
xticks(-100:5:100);
% Engine: compute a localized RMS
% Square the signal.
ySquared = y .^ 2;
% Get a moving average within a window
windowWidth = 121;
meanSquareY = movmean(ySquared, windowWidth);
% Take the square root of the mean square signal.
localRMSy = sqrt(meanSquareY);
% Plot those
subplot(2, 1, 2);
plot(x, ySquared, 'b-', 'LineWidth', 2);
hold on;
plot(x, localRMSy, 'r-', 'LineWidth', 2);
caption = sprintf('Local RMS in a moving window of width %d', windowWidth);
title(caption, 'FontSize', fontSize);
ylabel('Signal', 'FontSize', fontSize);
xlabel('x', 'FontSize', fontSize);
grid on;
ax = gca;
ax.XAxisLocation = 'origin';
ax.YAxisLocation = 'origin';
xticks(-100:5:100);
legend('y squared', 'local RMS');
% Set up figure properties:
% Enlarge figure to full screen.
set(gcf, 'Units', 'Normalized', 'OuterPosition', [0, 0, 1, 1]);
% Get rid of tool bar and pulldown menus that are along top of figure.
% set(gcf, 'Toolbar', 'none', 'Menu', 'none');
% Give a name to the title bar.
set(gcf, 'Name', 'Demo by ImageAnalyst', 'NumberTitle', 'Off')