summation without using any loop algorithm

조회 수: 2 (최근 30일)
monkey_matlab
monkey_matlab 2015년 5월 24일
답변: Walter Roberson 2015년 5월 24일
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
Geoff Hayes
Geoff Hayes 2015년 5월 24일
monkey_matlab - how have you defined k and t?
monkey_matlab
monkey_matlab 2015년 5월 24일
k = 1:3;
t = linspace(0, 4*pi, 100);

댓글을 달려면 로그인하십시오.

채택된 답변

Walter Roberson
Walter Roberson 2015년 5월 24일
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개)

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by