Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a better way to implement this MATLAB code?

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

like image 510
krishna Avatar asked Feb 22 '16 21:02

krishna


People also ask

Does compiled MATLAB code run faster?

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.

Why is my MATLAB code so slow?

Because, the code requires more RAM than you have in your computer.


2 Answers

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;
like image 70
Daniel Avatar answered Oct 01 '22 22:10

Daniel


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.
like image 35
zeeMonkeez Avatar answered Oct 01 '22 20:10

zeeMonkeez