Wardruna
Wardruna

Reputation: 308

Matrix dimensions must agree error in Matlab?

I am writing a function which gives the frequency of the nth key of a piano. But I want the frequency to decay with time, like in real life. So I multiply my function with exp(-a * 5) where a is some number from 0 to 1. But it gives me an error:

Error using .*
Matrix dimensions must agree.

How can I solve this problem?

sr = 16000;
T = 2;  % seconds duration
t = 0:(1/sr):T; 
n = 1;
f = ((2^(1/12))^(n-49))*440;
a = 0:0.01:1;
y = exp(-a*5).*sin(2*pi*f*t);
plot(t, y);

Upvotes: 2

Views: 404

Answers (1)

Stewie Griffin
Stewie Griffin

Reputation: 14939

You are trying to multiply exp(-a*5) with sin(2*pi*f*t), element-by-element. That's only possible if the two vectors have the same size. In your code, t is 1x320001, while a is 1x101.

I guess what you want is:

sr = 16000;
T = 2; %  seconds duration
t = 0:(1/sr):T; 
n = 1;
f = ((2^(1/12))^(n-49))*440;
a = linspace(0,1,numel(t));
y = exp(-a*5).*sin(2*pi*f*t);
plot(t, y);

Note that I changed the definition of a to linspace(0, 1, numel(t)). linspace(a, b, n) creates a vector from a to b, with n elements. It's the easiest way to make sure the two vectors you're multiplying are the same size.

enter image description here

Upvotes: 2

Related Questions