Is there a better way to implement this MATLAB code?

Y = zeros(5000,10); y is a predefined vector of 5000 x 1 consisting of numbers from 1 to 10;

 for i= 1:size(Y,1) Y(i,y(i)) = 1; end 

Is there a better and easier way to implement this, since the rest of my code is vectorized and does not contain any loops for the loop

+6
source share
3 answers

You can use bsxfun:

 bsxfun(@eq,y,[1:10]) 

Instead of your code, you can create each line using y(i)==[1:10] , which is finally wrapped in bsxfun for vectorization.

Another idea is to calculate the index:

 Y((y-1).*5000+(1:5000).')=1; 
+6
source

You can use sub2ind :

 Y(sub2ind(size(Y), 1:size(Y, 1), y')) = 1; 

However, this may be a little 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 solution tic for jj = 1:1000 Y = double(bsxfun(@eq, y, 1:10)); end toc %Elapsed time is 0.187331 seconds. 
+2
source

Here's another approach: create a sparse matrix using y as the column indices, and then convert to full if necessary:

 Y = full(sparse(1:numel(y), y, 1, numel(y), 10)); 
+2
source

All Articles