Vectorising cell array operations

조회 수: 1 (최근 30일)
Simon
Simon 2013년 7월 25일
I have currently a series of polygons in my code, stored as m*2 arrays, where each 1*2 section is a point. these polygons are stored in a cell array called polys.
I need to flip all of these vertically, so the code i am currently using is
for i = 1:numel(polys)
polys{i}(:, 1) = m-polys{i}(:, 1)
end
Where m is the height of the region (and the y coords are stored in the first position (ie a pioint is (y, x), not (x, y))
I want to execute this whole loop in one line (probably using cellfun?), but im not sure how to do it??
  댓글 수: 2
Daniel Shub
Daniel Shub 2013년 7월 25일
Why do you want to do that? The for loop seems nice and clean and self documenting to me.
Simon
Simon 2013년 7월 26일
Various reasons that aren't worth going into. One if which being I'm doing everything I possibly can to remove all loops, for speed, but there are others

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

답변 (1개)

Daniel Shub
Daniel Shub 2013년 7월 26일
편집: Daniel Shub 2013년 7월 26일
Blindly removing loops for speed is an antiquated view of MATLAB based on the performance of versions over 10 years old prior to the introduction of the JIT accelerator. To fully optimize your code you will want to make use of the tools like the profile (but be aware that it disables the JIT accelerator).
Given all you want to do is remove the loop you could look into either doing the task recursively or using CELLFUN. Neither are likely to give you a substantial speed up (and are likely to actually slow things down) and will be less readable than your simple loop.
For example, with cellfun
polys{1} = randn(5);
polys{2} = randn(6);
polys{3} = randn(7);
m = 10;
polys = cellfun(@(x)[m-x(:, 1), x(:, 2:end)], polys, 'UniformOutput', false);
  댓글 수: 2
Simon
Simon 2013년 7월 26일
I did mention that I wanted to use cellfun, I can't get it to work... I had an anonymous function declared but it wasn't working at all
Daniel Shub
Daniel Shub 2013년 7월 26일
See my edit, but again I see no advantage to doing this. It is unlikely to be faster.

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

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by