10

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:
2
  • 1
    Be aware: iteration is usually not "the Matlab way to do it". Most uses of iteration in other languages (like Python) are more elegantly and efficiently expressed in Matlab as matrix operations. Commented May 31, 2012 at 22:24
  • 2
    @RobertCooper Thats true only regarding arrays and matrices. If I had 10 images or different sizes, and had to do the same operation on each of them, I would like to loop in the for _ in list format. Commented Mar 22, 2014 at 17:20

3 Answers 3

16

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).

Sign up to request clarification or add additional context in comments.

Comments

3

Please try the following code.

 vs = [1 12 123 1234];
    for v = vs
        disp(v)
    end

Comments

0

Building on @tmpearce 's answer, a little trick I've found is to use:

for i = values(:)'
    #% i iterates through each element of 'values'
end

The colon operator ensures the array is a column vector, then transposing it gives you a row vector.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.