Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FOR loop over column vector vs row vector [duplicate]

I was just writing a "kinda-foreach" loop in Matlab and encountered this strange behavior:

I have the matrix A:

A = [
 3
 9
 5
 0];

And I want to use a foreach loop (as explained here) on the A.

If I write this:

for i = A
     disp('for')
     i    
end

The result will be:

for

i =

     3
     9
     5
     0

But when I use the transpose, the result will change:

for i = A'
     disp('for')
     i    
end

Result:

for

i =

     3

for

i =

     9

for

i =

     5

for

i =

     0

Which is the result I want.

Can anybody explain what's going on here? What's the difference between these two cases?

like image 652
Mahm00d Avatar asked Jul 31 '13 09:07

Mahm00d


2 Answers

when you type

A = [
3
9
5
0];

you create a column vector. Because Matlab iterates over columns you get one answer (the first column). By transposing it you get a row vector with 4 columns and therefore 4 answers each with one column.

like image 178
ipa Avatar answered Nov 19 '22 12:11

ipa


In Matlab, the for loop iterates over columns. http://www.mathworks.es/es/help/matlab/ref/for.html

like image 5
Luis Mendo Avatar answered Nov 19 '22 13:11

Luis Mendo