Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a Matlab loop equivalent to python's "for in" loop?

Tags:

matlab

Is there a matlab equivalent of the "for in" loop in python?

For instance in python, I can iterate through items of a list using the following code:

for c_value in C_VALUES:
like image 395
stressed_geek Avatar asked May 31 '12 22:05

stressed_geek


People also ask

Are there for loops in Matlab?

Matlab provides various types of loops to handle looping requirements including: while loops, for loops, and nested loops.

Can we use while loop inside for loop in Python?

Nested for Loops in PythonYou can put a for loop inside a while, or a while inside a for, or a for inside a for, or a while inside a while.

What is the difference between a for loop and a while loop in Matlab?

For loops require explicit values in order to function. These values can be predefined or stated within the loop. While loops will execute code as long as the condition part of the loop is true.


2 Answers

In MATLAB, for iterates over the columns of a matrix. Pretty much the same as your example, if C_VALUES were a row.

for val = row_vec
    #% stuff in the loop
end

is the MATLAB syntax. val will take on the values of row_vec as it iterates. The syntax you will often see (but isn't strictly necessary) is

for ii = 1:length(values)
    val = values(ii);
    #% stuff in the loop using val
end

Here, 1:length(values) creates a row vector [1 2 3 ...], and ii can be used to index into values.

(Note: i is another common choice, but as soon as you use i in this type of context where it is assigned a value, you don't get to use it in the imaginary number sense anymore).

like image 51
tmpearce Avatar answered Oct 22 '22 13:10

tmpearce


Please try the following code.

 vs = [1 12 123 1234];
    for v = vs
        disp(v)
    end
like image 22
Dmitriy Gorelov Avatar answered Oct 22 '22 12:10

Dmitriy Gorelov