simple for loop problem

41 visualizzazioni (ultimi 30 giorni)
Josiah Miles
Josiah Miles il 22 Ott 2019
Modificato: Walter Roberson il 11 Ott 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 Commenti
per isakson
per isakson il 22 Ott 2019
Sounds like homework. What you done so far and what's your problem?
Jia-Cheng
Jia-Cheng il 11 Ott 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

Accedi per commentare.

Risposte (2)

Maz M. Khansari
Maz M. Khansari il 23 Ott 2019
Modificato: Walter Roberson il 11 Ott 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 il 8 Nov 2023
Modificato: Walter Roberson il 11 Ott 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>

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by