Calculating values from a sequence with a for loop
    12 visualizaciones (últimos 30 días)
  
       Mostrar comentarios más antiguos
    
    Ryan Bowman
 el 8 de Dic. de 2018
  
    
    
    
    
    Comentada: madhan ravi
      
      
 el 8 de Dic. de 2018
            I'm trying to to calculate the first 100000 values of the sequence a_n = (2.2*n-1)^2 (with n=1,2,3,4,...etc) with a for loop. I cannot find out why I can't get the values I want into a column vector. I'm also just trying to display the first 10 values I get to the command window. Here is my code:
num = 100000;
n = 1;
AnLoop = zeros(1,100000);
for nLoop = 1:num
    AnLoop = (2.2.*n-1).^2;
    n = n+1;
end
disp('The first 10 values of this sequence is: ')
fprintf('%d\n', AnLoop)
0 comentarios
Respuesta aceptada
  madhan ravi
      
      
 el 8 de Dic. de 2018
        
      Editada: madhan ravi
      
      
 el 8 de Dic. de 2018
  
      With Loop:
num = 100000;
n = 1:100000;
A = zeros(100000,1);
for nLoop = 1:num
    A(nLoop,1) = (2.2.*n(nLoop)-1).^2;
end
disp('The first 10 values of this sequence is: ')
fprintf('%d\n', A(1:10))
%or
disp(A(1:10))  % to disp values
Without Loop:
num = 100000;
n = 1:100000;
A=((2.2.*n-1).^2).';
disp('The first 10 values of this sequence is: ')
fprintf('%d\n', A(1:10))
disp(A(1:10))  % to disp values
2 comentarios
Más respuestas (0)
Ver también
Categorías
				Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!