0

I need to write the code that turns a row vector into a matrix. For example, if I had a = 1 2 3 4 5 6 7 8 9, I want the matrix to be:

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

I have this, which doesn't work. Can anyone please assist me?

for i=1:length(a) m = a(i); i = i + 1; end 

Moreover, I am not allowed to use any of Matlab's built-in functions (such as reshape).

4
  • 1
    I can't use vec2mat or reshape Commented Oct 7, 2015 at 5:14
  • 1
    If your vector was 1x8, would the matrix be 2x4, or 4x2? Or is it only for 3x3? If you create a matrix of zeros of the size you want the result to be (for example, A=zeros(3,3)) then you can do A(:)=a. You will have to check whether the elements go to the right places in the matrix. Commented Oct 7, 2015 at 5:19
  • 1
    Posting homework assignments is usually not well received on SO, but as you showed what you have tried, +1 =) Have a look at Shai's edit to your question (you can click the "edited x minutes ago" link). Your original loop was not pretty =) Commented Oct 7, 2015 at 6:15
  • A note here, for loops automatically steps up the loop index. The loop statement for i= 1:length(a) in Matlab is similar to what in java or c++ is for (int i=1; i<=length(a); i++). However, one can assume that the implementation is more sophisticated than that since for i=a would perform a similar behaviour to for (T t : a), where T is its type. So the point is that you do not need to increment i in the loop. It is done implicitly in a for loop. Commented Oct 7, 2015 at 7:11

2 Answers 2

4

Use reshape

a = [1 2 3 4 5 6 7 8 9]; A = reshape(a, 3, [])' 

where the third argument is taken automatically (the number of cols)

Or if you cannot use any MATLAB build in function use this here

A = zeros(3,3); %// or A(3,3) = 0 by thewaywewalk (thank you) A(:) = a; A = A'; 
Sign up to request clarification or add additional context in comments.

4 Comments

I can't use any MATLAB functions.
in case zeros is also a forbidden function, you could use A(3,3) = 0 for pre-allocation.
@thewaywewalk Are there any case where zeros(N,M) actually is preferred over A(N,M) = 0;? zeros is of course safer, since this will not modify an existing variable. But still if you are in this situation you are pretty much screwed anyway.
3

Of course, using reshape is the right way to convert a vector into a matrix.
However, since you do not want to use any Matlab function, you can use a loop

A = zeros(3,3); %// preallocate for ii=1:3, A(ii,:) = a( (ii-1)*3 + 1:3 ); %// put one row into place end 

Or, more generally, if you want to reshape a H*W vector into a H-by-W matrix:

A = zeros(H,W); for ii=1:H A( ii, : ) = a( (ii-1)*W + 1:W ); end 

PS,
Note that it is best not to use i as a variable name in Matlab.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.