1

I have a matrix I, and I want to accumulate in an array A, for each value in I, an interval accordingly to those values in I lets call them i and j.

function acc(i,j)
  global A
  A(i:j) = A(i:j)+1;
end

However, passing and returning the arrays take too much time, because I execute the function many times, and it is not as simple as that example.

Is there any way of speeding it up? How can I pass an return those values without global?

adn
  • 897
  • 3
  • 22
  • 49
  • Possible duplicate of http://stackoverflow.com/q/1258761/426834 – zellus Nov 25 '10 at 07:08
  • If we suggest improvements to your simple example, won't you just post again to explain why they are inadequate for what you are really trying to do ? How can you expect real help with your real problem if you try to protect us from it ? – High Performance Mark Nov 25 '10 at 07:24
  • 2
    Have a look at this answer http://stackoverflow.com/questions/1258761/do-i-conserve-memory-in-matlab-by-declaring-variables-global-instead-of-passing-t/1261429#1261429 to write acc as nested function. @zellus: I agree - all answers have already been given. – Jonas Nov 25 '10 at 12:46
  • @Jonas: thx the nested function solve my problem.. it speed up the algorithm – adn Nov 26 '10 at 02:56

1 Answers1

1

The link in the comments proposes using a nested function as a solution. If the function you're using has use in several different places you may not want to nest in each place. It that case, I'd try to make the function modify in place.

http://blogs.mathworks.com/loren/2007/03/22/in-place-operations-on-data/

function A = acc(A,i,j)
  A(i:j) = A(i:j)+1;
end

This should not need to make a copy provided you meet the requirements set forth in Loren's blog post.

Rich C
  • 3,164
  • 6
  • 26
  • 37