simple for loop problem

조회 수: 22 (최근 30일)
Josiah Miles
Josiah Miles 2019년 10월 22일
편집: Walter Roberson 2024년 10월 11일
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