0

XWe have been assigned a task in which we want to concatenate several column vectors into a large matrix inside a for-loop. We wrote a little example program to try to find out what it was that didn't work, and we got pretty stuck.

In this example program, we want our matrix X (that's originally an empty matrix) to be a 5 X 5 matrix with only ones in it. We did this using a for loop, and we returned the value X ultimately, but it was still an empty matrix/vector. Below is our syntax;

    X = [];

    for i=1:5,
        X = horzcat(X, [1 1 1 1 1]');
    end

    X
zacdawg
  • 35
  • 5
  • You are not assigning anything to `X` inside the loop. Use `X = horzcat(X, [1 1 1 1 1]');`. – mikkola Dec 04 '15 at 13:59
  • 2
    @zacdawg Hey dawg, this is the best advice that will help you with lots of MATLAB stuff, not only with `horzcat`: 1. mark the function name (`horzcat` in this case) 2. Press [F1], 3. Read the syntax, 4. Read/run the examples, 5. If you're curious, read the rest. –  Dec 04 '15 at 14:01
  • Yes, I saw that. I just wrote it wrong on stack overflow, I edited it now - it still doesn't work :'( – zacdawg Dec 04 '15 at 14:02
  • 3
    How do you mean it does not work? I get a 5x5 matrix of ones running your fixed code. – mikkola Dec 04 '15 at 14:03
  • 3
    @zacdawg By the way, you might also want to [avoid using `i` or `j` as loop variables](http://stackoverflow.com/questions/14790740/using-i-and-j-as-variables-in-matlab/14790765#14790765). – mikkola Dec 04 '15 at 14:06
  • 2
    See also: [`ones`](http://www.mathworks.com/help/matlab/ref/ones.html) – sco1 Dec 04 '15 at 14:09

0 Answers0