0

I have the following loop that does what I need:

> whos Y
  Name       Size               Bytes  Class     Attributes

   Y         10x5000            400000  double              

> whos y
   Name         Size            Bytes  Class     Attributes

   y         5000x1             40000  double              

Y = zeros(K,m);
for i=1:m
    Y(y(i),i)=1;
end

I would like to vectorize it and I have tried without success e.g.

Y = zeros(K,m);
Y(y,:)=1;

The idea is to get a vector of:

y = [9, 8, 7, .. etc]

and convert it to:

Y = [[0 0 0 0 0 0 0 0 1 0]' [0 0 0 0 0 0 0 1 0 0]' [0 0 0 0 0 0 1 0 0 0]' ... etc]

this I need in the context of a multi-class ANN implementation.

SkyWalker
  • 13,729
  • 18
  • 91
  • 187

2 Answers2

1

Here's one solution you could use. It's a starting point from which you could optimise

k = 10;
n = 20;
y = randi(k, 1, n);

columns = 1:n;
offsets = k*(columns-1);
indices = offsets + y;

Y = zeros(k, n);
Y(indices) = 1
Huguenot
  • 2,427
  • 2
  • 17
  • 14
1

Have you considered using sparse matrix?

n=numel(y);
Y = sparse( y, 1:n, 1, n, n );

If you really must have the full matrix, you can call

Y = full(Y);
Shai
  • 111,146
  • 38
  • 238
  • 371