How to implement a for loop over a specified range?

Outputs:
  • t: time vector ranging from Start to End with a sampling rate of fs
  • X: sum of sinusoids over the specified range
The code I am using for my outputs is:
t = linspace(Start,End,fs);
X=0;
for i=1:N
X = X + A(i)*cos(2*pi*f(i)*t + phi(i)) + B(i);
end
I keep getting an error: Attempted to access B(2); index out of bounds because numel(B)=1. Need help fixing it.

2 comentarios

We do not know how you initialized B, or what it is intended to mean.
Did you happen to compute B using the "/" operator?
Brian Aguilar
Brian Aguilar el 1 de Mzo. de 2016
Editada: Walter Roberson el 1 de Mzo. de 2016
I got the same error for A too. Both B and A are N*1 matrix, where N is a integer, and positive. This is how I coded and initialized both A and B.
A = [N,1];
if ~all(isreal(A)) || ~all(A>0)
error('Amplitude must be real and postive elements');
end
B = [N,1];
if ~all(isreal(B))
error('B must be real and postive elements');
end

Iniciar sesión para comentar.

 Respuesta aceptada

The code you posted would result in A and B being scalars (length 1) if N is empty. If N was not empty, then A and B would only be of length 2 anyhow.
If you are trying to initialize A to be a vector of length N then you would use something like
A = zeros(N, 1);
... but then it would be all zero, which doesn't sound very meaningful.

3 comentarios

Maybe instead of using zeros, how could I could use random values that create a N * 1 matrix. How could I code that, so lets say N is equal to 10, and then A is equal to a 10 * 1 matrix. How could I make A be assigned to random values that generate a vector length of 10 rows and 1 column?
thanks for your help, I understand it a lot better now

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.

Etiquetas

Preguntada:

el 27 de Feb. de 2016

Comentada:

el 1 de Mzo. de 2016

Community Treasure Hunt

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

Start Hunting!

Translated by