For loop with vertical vs horizontal array

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

 채택된 답변

Image Analyst
Image Analyst 2012년 12월 11일

0 개 추천

I agree it's confusing at first. However it is documented in the "for" section:
for index = 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.
In your sexcond case, n is 1 - one column so the loop executes only once. In your first case, n was 4 - four columns so the loop executed 4 times.

댓글 수: 5

Ok, fair enough. I guess no smart way of making sure I get a linear indexing effect regardless of the valArray other than something like:
for index = reshape( 1, numel(valArray) )
in which case I probably prefer:
for i = 1:numel(valArray)
element = vallArray(i)
If you are using indices then use
for index = 1 : numel(valArray)
If you are using array values and do not know the orientation then
for index = valArray(:).'
Chris
Chris 2012년 12월 11일
Thanks, that is much nicer. Is the . in the .' necessary? If so what does it do differently than a simple '
Walter Roberson
Walter Roberson 2012년 12월 11일
The simple ' is conjugate transpose, in which the signs of the complex part of values are reversed. The .' operator is plain transpose.
Chris
Chris 2012년 12월 11일
got it, thanks

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Walter Roberson
Walter Roberson 2012년 12월 11일

0 개 추천

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.

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

질문:

2012년 12월 11일

Community Treasure Hunt

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

Start Hunting!

Translated by