8

It seems like this should be easy, but I'm no expert and google isn't helping.

I would like an elegant way in Matlab of producing the standard ordered basis vectors for an n-dimensional space. For example, behaviour similar to the following:

>> [e1, e2] = SOB(2);
>> e1

  e1 =    1     0

>> e2

  e2 =    0     1

I'm hoping for a 1-liner and don't really want to write a function for something so simple.

Thanks

des4maisons
  • 1,791
  • 4
  • 20
  • 23

4 Answers4

22

Why not

A = eye(N); 

then A(:,i) is your i-th basis vector

Aliaksei Kliuchnikau
  • 13,589
  • 4
  • 59
  • 72
Gunnar
  • 236
  • 2
  • 2
8

To obtain a single basis vector, say the k-th standard basis vector in N dimensions, you can use:

yourbasisvector = double(1:N == k)

1:N produces the vector 1 2 ... N, which == k element-wise tests for equality with k; double converts the logical values to numbers.

Thales
  • 585
  • 3
  • 9
  • 1
    This is amazing. I've been trying to either come up with, or find, a solution like this one for weeks. You can even extend this approach by doing `double(1:N == [k1, k2, k3]')` to get multiple identity vectors at once. – Mark Rucker Aug 22 '18 at 15:24
5

Would two lines be ok? Create the identity matrix with EYE, copy vectors into a cell array using MAT2CELL, then distribute them with DEAL.

tmp = mat2cell(eye(N),N,ones(N,1));
[e1,e2,...,eN] = deal(tmp{:})
Jonas
  • 74,690
  • 10
  • 137
  • 177
  • 2 lines could work... Though (to me) that is rather cryptic :) – des4maisons Jan 21 '11 at 02:55
  • @des4maisons: I have edited a bit to clarify. Basically, if you combine basis vectors into an array, you get the identity. So I construct the identity matrix and take it apart. – Jonas Jan 21 '11 at 02:58
  • Yah, I figured that was the way to do it, I just didn't know how, so thanks. Also, did you mean to link to mat2cell, or use num2cell? – des4maisons Jan 21 '11 at 03:01
  • @des4maisons: oops, it should be mat2cell. Thanks for pointing it out. – Jonas Jan 21 '11 at 03:03
0

if you anonymous function, it is more convenient.

e = @(x) eye(size(A))(:,x);

If the size of A is 6 by 6, this returns 6 by 1 vector.

e(1) = [1;0;0;0;0;0]
Miae Kim
  • 1,713
  • 19
  • 21