simple for loop problem

41 views (last 30 days)
Josiah Miles
Josiah Miles on 22 Oct 2019
Edited: Walter Roberson on 11 Oct 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 Comments
per isakson
per isakson on 22 Oct 2019
Sounds like homework. What you done so far and what's your problem?
Jia-Cheng
Jia-Cheng on 11 Oct 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

Sign in to comment.

Answers (2)

Maz M. Khansari
Maz M. Khansari on 23 Oct 2019
Edited: Walter Roberson on 11 Oct 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 on 8 Nov 2023
Edited: Walter Roberson on 11 Oct 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>

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!