I have a 2D matrix, say M=zeros(10,10);
I have another column matrix, V=[1;2;3;4;5;6;5;4;3;2];
I would like to be able to set M(i,j) = 1 for all j >= V(i)
I know I can do this in a loop
for i=1:10
M(i,V(i):10) = 1;
end
but it seems that it would be possible to use some form of Matlab indexing to avoid using a loop. For example something like :
M(:,V:10)=1;
or
M(:,V(:):10)=1;
but neither of these produces the expected result.
Is there some syntactic sugar I can use to achieve this or should I revert to looping?
Since you’re looking for syntactic sugar, here’s a sort of esoteric way of doing it. 🙂
Assuming the length of
Vis the size of both dimensions in the desired matrixM, first create an identity matrix of the same size, then index appropriately and takecumsum:Ok, now: less fun, but (on my machine) faster than any of the other options that have been tested so far: