simple for loop problem

41 次查看(过去 30 天)
Josiah Miles
Josiah Miles 2019-10-22
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 个评论
per isakson
per isakson 2019-10-22
Sounds like homework. What you done so far and what's your problem?
Jia-Cheng
Jia-Cheng 2024-10-11
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

请先登录,再进行评论。

回答(2 个)

Maz M. Khansari
Maz M. Khansari 2019-10-23
编辑:Walter Roberson 2024-10-11
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 2023-11-8
编辑:Walter Roberson 2024-10-11
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>

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by