I have an error with this code for different number of elements. I'm lost on how to fix it for the proper output.

1 visualizzazione (ultimi 30 giorni)
clc;
clear all
close all
% Define the data points for the base excitation (modify these values as needed)
data = [0.0; 0.00571634384576599; 0.0172961399245937; 0.0215661733228299;
0.0138433053175935; 0.00475824598689792; 0.00940235333989425;
0.0298244388227628; 0.0502561943723699; 0.0516260538077677;
0.0311672997795811; 0.00657207675777726;
-0.00043850430233673; 0.0150661812622991; 0.0369781637016863;
0.0444861334353839; 0.032063551445643; 0.0130695841363085;
0.00450012342523607; 0.00980150594910536; 0.0175350556867159;
0.0158705130787799; 0.00603906690334467; 0.0];
% Sampling period (modify this value if needed)
T = pi/2; %seconds
% Number of data points
N = 24;
% Fundamental frequency (reciprocal of sampling period)
f0 = 1/T;
% Define the number of harmonics to consider (modify this value if needed)
numHarmonics = 4;
% Pre-allocate arrays for coefficients with correct sizes
a = zeros(1, numHarmonics+1);
b = zeros(1, numHarmonics);
% Calculate the constant term (a0)
a(1) = mean(data); % Assigning the average to the first element of a
% Calculate the coefficients for harmonics (a1 to aN and b1 to bN)
for n = 1:numHarmonics
% Calculate the cosine terms
cosine_terms = data .* cos(n*2*pi*f0*(0:N-1)/T);
% Calculate the sine terms (omit the first term for b because of symmetry)
sine_terms = data(2:end) .* sin(n*2*pi*f0*(1:N-1)/T);
% Apply integration by trapezoidal rule (assuming uniform sampling)
a(n+1) = (sum(cosine_terms) + cosine_terms(1)/2 + cosine_terms(end)/2) * 2/N;
b(n) = (sum(sine_terms) + sine_terms(1)/2) * 2/N;
end
% Display the Fourier Series Coefficients
fprintf('Fourier Series Coefficients:\n');
fprintf('a0 = %.4f\n', a(1));
for n = 1:numHarmonics
fprintf('a%d = %.4f, b%d = %.4f\n', n, a(n+1), n, b(n));
end
Output:
Unable to perform assignment because the left and right sides have a different number of elements.
Error in fouriercodething (line 40)
a(n+1) = (sum(cosine_terms) + cosine_terms(1)/2 + cosine_terms(end)/2) * 2/N;

Risposta accettata

Voss
Voss il 29 Apr 2024

Transpose the (0:N-1) vector, because you want a column vector, in order to be consistent with the shape of the data variable, which is also a column vector. With the transpose, the result is a column vector; without, it's a matrix, which causes the error later on.

cos(n*2*pi*f0*(0:N-1).'/T)
%                    ^^ transpose 

Same for the (1:N-1) vector a couple of lines later.

Più risposte (0)

Categorie

Scopri di più su Mathematics and Optimization in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by