Is there any way to make this code faster?

Hi, I have this code that tosses out pixels from a cc list
for i = 1:cc.NumObjects
for j = length(cc.PixelIdxList{i}):-1:1
ind = cc.PixelIdxList{i}(j);
if ~imdiff(ind) || ~imcombined(ind)
cc.PixelIdxList{i}(j) = [];
end
end
end
imdiff and imcombined are both images. The code at the moment takes quite a while to churn through a decent sized image. Is there any way to make this code run faster?

 채택된 답변

Daniel Shub
Daniel Shub 2012년 7월 17일

0 개 추천

I think this is a memory allocation issue. Every time you set cc.PixelIdxList{i}(j) = [], MATLAB needs to allocate new memory. You might be better off building an array that holds the indices to remove, and then removing them at the end.

댓글 수: 1

Thanks! I tried what you suggested and it reduced the execution time by a ton! Here's the revised code:
for i = 1:cc.NumObjects
indices = false(length(cc.PixelIdxList{i}));
for j = 1:length(cc.PixelIdxList{i})
ind = cc.PixelIdxList{i}(j);
if ~imdiff(ind) || ~imcombined(ind)
indices(j) = true;
end
end
cc.PixelIdxList{i}(indices) = [];
end
This works great but if you have any other suggestions to make it run even faster, please tell!

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Sean de Wolski
Sean de Wolski 2012년 7월 17일
편집: Sean de Wolski 2012년 7월 17일

0 개 추천

That whole thing should be vectorizable assuming imdiff and imcombined (whatever those are) can handle it:
cellfun(@(c)c(imdiff(c)&imcombined(c)),CC.PixelIdxList,'uni',false)

댓글 수: 3

C.J. Harris
C.J. Harris 2012년 7월 17일
Hmm.. is there any point using cellfun here? Does it increase speed or readability? At least in 2006b I find very few circumstances where cellfun gives improved performance over a simple loop.
Sean de Wolski
Sean de Wolski 2012년 7월 17일
No. I just like it :)
You could keep the outer for-loop just as easily. The point is that the inner for-loop does not need to check each value if imdiff and imcombined are either images or functions that can be passed vector inputs.
Qingyang
Qingyang 2012년 7월 17일
Hi, thanks for the reply. I'm not quite familiar with that type of coding, but it did not give what I intended when I used it in place of the original code. I'm sure its probably just a small tweak that I'm can't tell. But, thanks anyways and I've got the code working much faster based on a suggestion from another commenter.

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Mathematics에 대해 자세히 알아보기

질문:

2012년 7월 17일

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by