MATLAB Efficiently Extract Vector from MATLAB Matrices

AI Thread Summary
The discussion revolves around extracting individual column vectors from a 3x3 matrix in MATLAB. The user attempts to use a for loop to create separate vectors (a1, a2, a3) from the columns of the matrix A. However, the current approach results in only the last vector being stored, as the loop continuously overwrites a single variable (a_i). The key point is that MATLAB does not automatically create separate variables based on loop indices. Instead, a suggestion is made to consider whether it's necessary to break the matrix into separate vectors, as keeping the data in matrix form may be more efficient. The conversation highlights the importance of understanding variable assignment and indexing in MATLAB programming.
omri3012
Messages
60
Reaction score
0
Hallo,

I have a 3*3 matrices in matlab:

A=[ 1 2 3; 4 5 6; 7 8 9];

and i won't to accept a vector from each colume in an easy way, i.e.

a1=1 2 3 , a2=4 5 6 , a3=7 8 9
so i tried to wrote:

for i=1:3
a_i=A(:,i);
end

but i only the last vector, a3=7 8 9...

if anyone have a good suggestion it would be very helpful.

thnks
Omri
 
Physics news on Phys.org
omri3012 said:
Hallo,

I have a 3*3 matrices in matlab:

A=[ 1 2 3; 4 5 6; 7 8 9];

and i won't to accept a vector from each colume in an easy way, i.e.

a1=1 2 3 , a2=4 5 6 , a3=7 8 9
so i tried to wrote:

for i=1:3
a_i=A(:,i);
end

but i only the last vector, a3=7 8 9...

if anyone have a good suggestion it would be very helpful.

thnks
Omri

Your problem is with the for loop not doing what you think it's doing. When you say

Code:
for i = 1:3
    a_i = A(:, i);
end

you are not declaring three separate vectors a_1, a_2, a_3 and assigning them the rows of A. What you are doing is declaring a vector a_i and successively redefining it to be equal to each row of A, so that by the end of the for loop you have a_i = A(3,:). In other words, simply putting '_i' at the end of a vector isn't how you subscript vectors within Matlab.
 
thanks for ypur responde,

i understand what you are saying, but is there a loop or other command
that generate 3 vectors a_1, a_2, a_3 from the matrices A?
 
Back
Top