summation without using any loop algorithm
7 views (last 30 days)
Show older comments
monkey_matlab
on 24 May 2015
Answered: Walter Roberson
on 24 May 2015
Hello,
I am trying to implement the summation for a square wave without the use of loops. I have the following code:

sona = sin((2*k - 1)'*t)./(2*k - 1);
but keep getting the error: "Error using * Inner matrix dimensions must agree"
Can you please explain what the problem is and how I can fix this error?
Thanks, monkey_matlab
2 Comments
Accepted Answer
Walter Roberson
on 24 May 2015
Suppose that your k is a row vector of 1:n
k = 1:n;
and suppose that your t is a row vector of length L
L = 50;
t = linspace(0,20,L);
then
(2*k-1)' * t
would be well defined and would be of size n x L. You can sin() that and the result will stay n x L. Now you are trying to divide it by the row vector (2*k-1). An n x L matrix cannot be divided by a 1 x n row vector. So you need to extend the 1 x n row vector into an n x L matrix in order to do the division:
repmat((2*k-1)', 1, L)
now you can do element-by-element division, and that is going to give you an n x L result. If you now sum along the first dimension, you would get a 1 x L result:
n = 16; %number of harmonics
startat = 0; %start and stop times
endat = 20;
L = 50; %how many time points
k = 1:n;
k21 = 2*k - 1;
t = linspace(0,20,L);
sona = sum(sin(k21' * t) ./ repmat(k21', 1, L), 1);
plot(t, sona)
0 Comments
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!