how to velocize it (vectorizing)
이전 댓글 표시
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
답변 (1개)
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
Bruno Luong
2023년 8월 20일
편집: Bruno Luong
2023년 8월 20일
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
2023년 8월 20일
편집: Bruno Luong
2023년 8월 20일
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
2023년 8월 20일
편집: Bruno Luong
2023년 8월 20일
"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.
카테고리
도움말 센터 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!