How to write FOR LOOP in Matlab?

6 次查看(过去 30 天)
nancy
nancy 2014-11-25
Hi;
Could you please explain below code? I study on for loop in Matlab to learn. I use generally tutorials from the Internet. I have seen below code in the Internet. But I could not understand what that code means.
A = [ [1 2 3]' [3 2 1]' [2 1 3]']
A =
1 3 2
2 2 1
3 1 3
for j=2:3,
A(j,:) = A(j,:) - A(j-1,:)
end
For example; What does "for j=2:3," row means?
What does "A(j,:) = A(j,:) - A(j-1,:)" means? I couldn't understand that as well.. Could you help me?
  1 个评论
the cyclist
the cyclist 2014-11-25
You might want to start with some very basic tutorials. For example, take a look at this page.

请先登录,再进行评论。

回答(2 个)

the cyclist
the cyclist 2014-11-25
The code
for j=2:3,
A(j,:) = A(j,:) - A(j-1,:)
end
means that you will run the middle line of code substituting the value j=2, and then you will run it substituting the value j=3.
So, it is the same thing as running the two lines of code
A(2,:) = A(2,:) - A(2-1,:)
A(3,:) = A(3,:) - A(3-1,:)
which is the same as
A(2,:) = A(2,:) - A(1,:)
A(3,:) = A(3,:) - A(2,:)
The colons in the second argument mean "do this for the whole row". It is a vector operation.

Meghana Dinesh
Meghana Dinesh 2014-11-25
[1 2 3]' means transpose of [1 2 3] so it becomes:
[1
2
3]
This is the first column of A Similarly, you get [3 2 1]' and [2 1 3]' to get the second and third columns of matrix
for j=2:3,
means "for j equal to 2, till 3, in steps of 1 (by default, it is in steps of 1). So j takes the values 2 and 3.
A(j,:)
Here, j takes the values 2 and 3. The syntax is: A(1st dimension,2nd dimension). The 1st dimension is row, 2nd dimension is column. So the row of A takes the value 2 in the first iteration and 3 in the second iteration.
Example: A(2,:) means 2nd row of A and all columns. So, in the A matrix defined above, you will get
A(2,:) = [2 2 1]

类别

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