Y = zeros(5000,10);
y
is a 5000 x 1 predefined vector consisting of numbers from 1 to 10;
for i= 1:size(Y,1)
Y(i,y(i)) = 1;
end
Is there a better and simpler way to implement this since the rest of my code is vectorized and does not contain any for loop
Compiling can accelerate your code by a factor 2, with some luck. Exploiting the underlying maths and improving the MATLAB code can give you a fctor of 100. You find some examples in the forum with 200 and 1000 times faster code in pure Matlab.
Because, the code requires more RAM than you have in your computer.
You could use bsxfun:
bsxfun(@eq,y,[1:10])
Instead of your code, you can create each row using y(i)==[1:10]
which is finally wrapped in bsxfun to vectorize.
Another idea would be index calculation:
Y((y-1).*5000+(1:5000).')=1;
You could use sub2ind
:
Y(sub2ind(size(Y), 1:size(Y, 1), y')) = 1;
However, this might actually be slightly slower:
Y = zeros(5000,10);
y = randi(10, 5000, 1);
tic
for jj = 1:1000
for i = 1:size(Y,1)
Y(i,y(i)) = 1;
end
end
toc
% Elapsed time is 0.126774 seconds.
tic
for jj = 1:1000
Y(sub2ind(size(Y), 1:size(Y, 1), y')) = 1;
end
toc
% Elapsed time is 0.139531 seconds.
% @Daniel's solution
tic
for jj = 1:1000
Y = double(bsxfun(@eq, y, 1:10));
end
toc
%Elapsed time is 0.187331 seconds.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With