-2

I want to generate a vector that looks like this: [1, 0, 0.... 0, 1], but I can't figure out how to do this without using a for. I can generate various matrix formats, but this one I can't figure out how should be done.

icebp
  • 1,608
  • 1
  • 14
  • 24

1 Answers1

6

Overwrite on a zero vector of the corresponding size.

x=zeros(1,n);
x(1)=1; x(n)=1;
karakfa
  • 66,216
  • 7
  • 41
  • 56
  • 6
    If `x` was not created before-hand, you can actually get away with just the second line of code. It's an undocumented MATLAB trick that most people don't know about (obviously as it's undocumented) and it is known to save time in terms of computation. You can find more about this by checking out this StackOverflow post: http://stackoverflow.com/questions/14169222/faster-way-to-initialize-arrays-via-empty-matrix-multiplication-matlab. Either way, +1. – rayryeng Apr 25 '16 at 14:56
  • 2
    @Crowley to do...what? – sco1 Apr 25 '16 at 15:34
  • @excaza to have wider picture? – Crowley Apr 25 '16 at 15:40
  • 2
    @Crowley I think excaza means to say how those functions would be applicable to this specific problem. That statement by itself given the context of the current question is unclear. It implies that you should look at those functions to generate the desired vector by the OP when it is rather unnecessary. You could perhaps generate the desired vector using `nan` and `ones`, but it's very unnecessary with `cell` and `deal`. You probably should have added a comment saying that you should look at these functions to further your MATLAB understanding instead. – rayryeng Apr 25 '16 at 15:44
  • 1
    @Crowley `A = cell(ones(1), n); [A{2:n-1}] = deal(NaN); A = [ones(1) cell2mat(A) ones(1)]; A(isnan(A)) = zeros(1);`? – sco1 Apr 25 '16 at 15:53