How to get a column vector from a 11x14 matrix?

So I have an 11x14 matrix 'Q' of values, and I would like to make one column vector 'b' from these values row by row. my code is as follows.
m=0
for i=2:10
for j=2:13
for m=m+1
for m=m+1
b(m)=Q(i,j);
end
end
end
the end result should be a 122x1 matrix but from my loop I end up getting a 217x1 matrix. What can I do to fix this?

Answers (1)

zephyr21 - when I run your code, my b is a 1x108 matrix. How do you get a 217x1 and why do you think that the result should be a 122x1? Since your i iterates from 2 through 10 and j iterates from 2 through 13, then b should be 9*12=108 elements.
In your code, I would remove the inner-most for loop and just replace this with
for j=2:13
m = m + 1;
b(m) = Q(i,j);
end
Also, try to avoid using i and j as the names of indexing variables (for your loops) since MATLAB uses both to represent the imaginary number.
And...you may want to look at reshape which can be used (for example) to reshape your matrix into a column vector.

4 Comments

zephyr21
zephyr21 on 14 Jun 2016
Edited: zephyr21 on 14 Jun 2016
I am not sure why I am getting a 217x1, I think it should be a 122x1 because I am using gmres to solve for unknowns in another matrix. My A matrix is a 122x122 so I figured the b matrix needs to be 1x122 transposed to 122x1 to solve for unknowns in x.
also, your loop did make a 122x1 but it left out pretty much all of the numbers in my 'Q' matrix
How could it create a 122x1 array and then leave out pretty much all of the numbers in my 'Q' matrix? What numbers are in the b if not those from Q?
And when I run the code
m = 0;
for i=2:10
for j=2:13
m = m + 1;
b(m) = Q(i,j);
end
end
b is a 1x108 array. How can you get the 122x1 array instead?
zephyr21
zephyr21 on 14 Jun 2016
Edited: zephyr21 on 14 Jun 2016
Ok, I am getting the 1x108 now after clearing the workstation window. I'm just trying to match my 'A' matrix in terms of rows so the gmres will work. My 'A' matrix is now a 121x121, so I need a 121x1 'b' and 'x' matrix for gmres to work correct? My code for 'A' matrix is as follows:
  • m=0
  • for i=2:10
  • for j=2:13
  • for m=m+1
  • A(m,m)=Center(i,j)
  • A(m+1,m)=West(i,j)
  • A(m,m+1)=East(i,j)
  • A(m+13,m)=South(i,j)
  • A(m,m+13)=North(i,j)
  • end
  • end
  • end
This gives me a 121x121 matrix, which I am now realizing is because of the m+13.
So what should the dimensions of A really be?

This question is closed.

Asked:

on 14 Jun 2016

Closed:

on 20 Aug 2021

Community Treasure Hunt

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

Start Hunting!