How to write FOR LOOP in Matlab?

6 Ansichten (letzte 30 Tage)
nancy
nancy am 25 Nov. 2014
Beantwortet: Meghana Dinesh am 25 Nov. 2014
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 Kommentar
the cyclist
the cyclist am 25 Nov. 2014
You might want to start with some very basic tutorials. For example, take a look at this page.

Melden Sie sich an, um zu kommentieren.

Antworten (2)

the cyclist
the cyclist am 25 Nov. 2014
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 am 25 Nov. 2014
[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]

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by