Tutorial by Examples

The simplest case is just preforming a task for a fixed known number of times. Say we want to display the numbers between 1 to n, we can write: n = 5; for k = 1:n display(k) end The loop will execute the inner statement(s), everything between the for and the end, for n times (5 in this ex...
The right-hand side of the assignment in a for loop can be any row vector. The left-hand side of the assignment can be any valid variable name. The for loop assigns a different element of this vector to the variable each run. other_row_vector = [4, 3, 5, 1, 2]; for any_name = other_row_vector ...
If the right-hand side of the assignment is a matrix, then in each iteration the variable is assigned subsequent columns of this matrix. some_matrix = [1, 2, 3; 4, 5, 6]; % 2 by 3 matrix for some_column = some_matrix display(some_column) end (The row vector version is a normal case of thi...
my_vector = [0, 2, 1, 3, 9]; for i = 1:numel(my_vector) my_vector(i) = my_vector(i) + 1; end Most simple things done with for loops can be done faster and easier by vectorized operations. For example, the above loop can be replaced by my_vector = my_vector + 1.
Loops can be nested, to preform iterated task within another iterated task. Consider the following loops: ch = 'abc'; m = 3; for c = ch for k = 1:m disp([c num2str(k)]) % NUM2STR converts the number stored in k to a charachter, % so it can be concatanet...
This is not something you will see in other programming environments. I came across it some years back and I couldn't understand why it was happening, but after working with MATLAB for some time I was able to figure it out. Look at the code snippet below: for x = 1:10 for x = 1:10 fpr...

Page 1 of 1