simple for loop problem

40 visualizaciones (últimos 30 días)
Josiah Miles
Josiah Miles el 22 de Oct. de 2019
Editada: Walter Roberson el 11 de Oct. de 2024
Create a for loop that adds one to every number in the array. For example [1,2,3] becomes [2,3,4] after the loop is complete.
a. create the variable x=1:10;
b. set the loop to run the correct amount of times
c. write the loop
d. use disp(x)
  2 comentarios
per isakson
per isakson el 22 de Oct. de 2019
Sounds like homework. What you done so far and what's your problem?
Jia-Cheng
Jia-Cheng el 11 de Oct. de 2024
x = [1:10]
x = 1×10
1 2 3 4 5 6 7 8 9 10
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
x_1 =0
x_1 = 0
for i = 1:length(x)
x_1= x_1 + x(i)+1
end
x_1 = 2
x_1 = 5
x_1 = 9
x_1 = 14
x_1 = 20
x_1 = 27
x_1 = 35
x_1 = 44
x_1 = 54
x_1 = 65
disp(x)
1 2 3 4 5 6 7 8 9 10

Iniciar sesión para comentar.

Respuestas (2)

Maz M. Khansari
Maz M. Khansari el 23 de Oct. de 2019
Editada: Walter Roberson el 11 de Oct. de 2024
The following will do the job for you.
x = 1:10;
x_new = zeros(1,numel(x));
for i=1:numel(x)
x_new(i) = x(i)+1;
end
disp(x);
1 2 3 4 5 6 7 8 9 10

Darshan
Darshan el 8 de Nov. de 2023
Editada: Walter Roberson el 11 de Oct. de 2024
x = [1:10]
x = 1×10
1 2 3 4 5 6 7 8 9 10
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
for i=1:10
new_x(i,:) = x(i)+1
end
new_x = 2
new_x = 2×1
2 3
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
new_x = 3×1
2 3 4
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
new_x = 4×1
2 3 4 5
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
new_x = 5×1
2 3 4 5 6
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
new_x = 6×1
2 3 4 5 6 7
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
new_x = 7×1
2 3 4 5 6 7 8
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
new_x = 8×1
2 3 4 5 6 7 8 9
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
new_x = 9×1
2 3 4 5 6 7 8 9 10
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
new_x = 10×1
2 3 4 5 6 7 8 9 10 11
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>

Categorías

Más información sobre Loops and Conditional Statements 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