Why this Octave code won't work?

Viewed 2526

Let Y be a vector of length N, containing numbers from 1 to 10. As example code you can use:

Y = vec(1:10);

I am writing the code which must create an N x 10 matrix, each row consisting of all zeros except for a 1 only in the position which corresponds to the number in vector Y. Thus, 1 in Y becomes 10000000000, 3 becomes 0010000000, and so on.

This approach works:

cell2mat(arrayfun(@(x)eye(10)(x,:), Y, 'UniformOutput', false))

My next idea was to "optimize", so eye(10) is not generated N times, and I wrote this:

theEye = eye(10);
cell2mat(arrayfun(@(x)theEye(x,:), Y, 'UniformOutput', false))

However, now Octave is giving me error:

error: can't perform indexing operations for diagonal matrix type
error: evaluating argument list element number 1

Why do I get this error? What is wrong?

Bonus questions — do you see a better way to do what I am doing? Is my attempt to optimize making things easier for Octave?

2 Answers
Related