# Sawtooth Wave Fourier Series- MATLAB issue

I have what I believe is the correct equation for my sawtooth wave However, I am having issues with representing it in MATLAB. I keep receiving an error message saying "Matrix dimensions must agree. Error in problem1_plot (line 7) basis = ((-1).^k).exp(jpi*k.*t);"

I tried looking at each part of the basis, and it seems the problem lies within the exp term. When I tried to run my code with only that part of the basis in, the same error message popped up. I'd appreciate any help in clarifying what the cause of this issue is.

t = linspace(0, 5);
k = -100:100;
x = (2*j)./(pi*k);

xm = repmat(X ,[1, length(t)]);

basis = ((-1).^k).*exp(j*pi*k.*t);
x100 = sum(xm.*basis);

tmin = min(t);
tmax = max(t);

plot(t,x100);

• Why have you got a period (.) after "(-1)" and before "^k". I know nothing about matlab so maybe this is normal because you seem to have this extraneous period (dot) in other places. – Andy aka Mar 26 at 8:26
• The dot is to allow for the operator to be applied by element – I'mReallyTired Mar 26 at 8:30
• Where are you defining your t array? – ZetaSeeker Mar 26 at 8:55
• oh, i just realized i forgot to copy that line, fixed the code – I'mReallyTired Mar 26 at 9:11
• I'm voting to close this question as off-topic because this is a general programming question, which should have been asked on Stackoverflow.com, not here. Also, just a typo, so would've been closed over there, too. – Marcus Müller Mar 26 at 9:19

It seems we are missing some of your code (e.g. how is capital X defined?). However, your guess is correct. There is an inherent issue with the k.*t operation in line seven. Namely, k has 201 elements (all integers from -100 to 100), while t is defined as 100 elements from 0 to 5 (default for linspace is to produce 100 elements). Thus you are attempting to multiply a (1×201) with a (1×100) matrix.

I am assuming the equation you have listed above is a summation of k values from -inf to inf, and you are providing an approximation with a relatively large but finite range of k from -100 to 100. One solution is to iteratively sum x100 for each value of k with a for loop. You must redefine x according to the value of k in the for loop. The iterating value k is listed in the code as ki. This script should produce the sawtooth wave you are hoping for. Best of luck!

k = -100:100;
t = linspace(0, 5);
x100 = zeros(1,length(t));
for ki = k
x = (2*1i)./(pi*ki);
x100 = x100 + x.*((-1).^ki).*exp(1i*pi*ki.*t);
end
tmin = min(t);
tmax = max(t);
plot(t,x100);