how to velocize it (vectorizing)
Show older comments
a=magic(10)
b=[4;5;9;2;3;4;2;7;4;9] %width(a) element
x=ones(size(a));
for i=1:numel(b)
x(1:max(b(i)-1,1),i)=0
end
Answers (1)
Bruno Luong
on 20 Aug 2023
Edited: Bruno Luong
on 20 Aug 2023
I don't know why a is matter beside that the first dimension is 10
a=magic(10);
b=[4;5;9;2;3;4;2;7;4;9]; %width(a) element
h = size(a,1);
x = double(ndgrid(1:h,b)>=b(:)')
;
9 Comments
Bruno Luong
on 20 Aug 2023
Edited: Bruno Luong
on 20 Aug 2023
The only thing my code requires is
numel(b) == width(a)
which obviously what you also have
b=[4;5;9;2;3;4;2;7;4;9] %width(a) element
Bruno Luong
on 20 Aug 2023
Edited: Bruno Luong
on 20 Aug 2023
a=200;%it's an example
x=ones(a,numel(b))
now you change a to be a size NOT a matrix as in your original question.
In my code I call it "h" and not "a".
How hard to be self consistent?
" with max(b)<h is equal.. with max(b)>=h it is different"
because in that case your code grows x beyond the initial dimension of height h. Your final x will have more than h rows. Do you really want to do that?
h=7
b=[4;5;9;2;3;4;2;7;4;9];
x=ones(h,numel(b));
for i=1:numel(b)
x(1:max(b(i)-1,1),i)=0;
end
x
x1 = double(ndgrid(1:h,b)>=b(:)')
isequal(x(1:h,:), x1)
As for speed I could possibly speed up, but who tells you that vectorized code must be faster?
Here is the timing on bigger arrays (I speed up the methods based on what you said about logical).
Yes for-loop is faster on online server (on my compter I get the opposite). The persons who claim for-loop is slow can come here and look or try to beat it.
h = 5710;
b=randi([0 h+1], 1, 82);
isequal(forloop(h, b), cmpb(h, b))
t_forloop = timeit(@()forloop(h, b), 1)
t_cmpb = timeit(@()cmpb(h, b), 1)
function x = forloop(h, b)
x=true(h,numel(b));
for i=1:numel(b)
x(1:max(b(i)-1,1),i)=false;
end
end
function x = cmpb(h, b)
x = (1:h)'>=b(:)';
end
Bruno Luong
on 20 Aug 2023
Edited: Bruno Luong
on 20 Aug 2023
"I've noticed dramatic improvements when it comes to vectorizing code where there is a loop inside another"
Not really. The speed depens what you do in the body of the loop(s), not loop are nested or not.
I know what I'm talking on speeding MATLAB code.
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!