Borrar filtros
Borrar filtros

summation without using any loop algorithm

1 visualización (últimos 30 días)
monkey_matlab
monkey_matlab el 24 de Mayo de 2015
Respondida: Walter Roberson el 24 de Mayo de 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 comentarios
Geoff Hayes
Geoff Hayes el 24 de Mayo de 2015
monkey_matlab - how have you defined k and t?
monkey_matlab
monkey_matlab el 24 de Mayo de 2015
k = 1:3;
t = linspace(0, 4*pi, 100);

Iniciar sesión para comentar.

Respuesta aceptada

Walter Roberson
Walter Roberson el 24 de Mayo de 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)

Más respuestas (0)

Categorías

Más información sobre MATLAB en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by