For loop with vertical vs horizontal array
Show older comments
Is the below difference intended functionality or a bug?
x = [1, 2, 3, 4];
for y = x
disp( 'Printing' );
disp( y );
end
Result:
Printing
1
Printing
2
Printing
3
Printing
4
Whereas if I transpose x, the loop only runs once with y = [1; 2; 3; 4].
x = [1, 2, 3, 4]';
for y = x
disp( 'Printing' );
disp( y );
end
Result:
Printing
1
2
3
4
Perhaps I'm being thick, but I can't find this behavior documented anywhere and I would have expected it to loop through the elements in the matrix/array as if it were one dimensional (linear indexing).
Accepted Answer
More Answers (1)
Walter Roberson
on 11 Dec 2012
It is deliberate behavior.
valarray : creates a column vector index from subsequent columns of array valArray on each iteration. For example, on the first iteration, index = valArray(:,1). The loop executes for a maximum of n times, where n is the number of columns of valArray, given by numel(valArray, 1, :). The input valArray can be of any MATLAB data type, including a string, cell array, or struct.
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!