user3216081
user3216081

Reputation: 3

MATLAB plotting error

I am trying to plot the following function:

enter image description here

The time interval is to be from 0 to 5 seconds using a step size of 0.002. This is what I have so far...

t = 0:0.002:5;
k = [2; 4; 6; 8];
i = (1/pi) + 0.5*sin(4*t) - (2/pi)*sum((cos(4*k*t))/(k*k-1));
plot(t,i)

It gives me the error:

Error using  * 
Inner matrix dimensions must agree.

Error in lab1_5 (line 4)
i = (1/pi) + 0.5*sin(4*t) -
(2/pi)*sum((cos(4*k*t))/(k*k-1));

I then tried every use of './' and '.*' but it still gives me the same error. What am I doing wrong?

Upvotes: 0

Views: 138

Answers (1)

herohuyongtao
herohuyongtao

Reputation: 50707

Change your code to:

t = 0:0.002:5;
k = [2; 4; 6; 8];

i = (1/pi) + 0.5*sin(4*t)
for j=1:4
    i = i-(2/pi)*((cos(4*k(j)*t))/(k(j)*k(j)-1));
end
plot(t,i)

The reason is that k is a col-vector (or a 4x1 matrix), so you cannot simply multiply it by k*k. For matrix multiplication, the size of left and right must follow n × m and m × p. In this case, you need to loop multiply every elements of k.

Upvotes: 1

Related Questions