Reputation: 5690
I am trying to streamline my code. I have a 2-column array from which I'd like to extract the averages of the columns and store them as X and Y.
I tried using the following code:
[x y] = mean(theArray);
...However, this returns
??? Error using ==> mean
Too many output arguments.
For now, I have settled with the three lines:
coords = mean(theArray);
x = coords(1);
y = coords(2);
I'm sure there must be a much simpler way of doing this in less than three lines. My code is running an eye tracking device at 1000Hz and I want to avoid any unnecessary processing...
Any wisdom gratefully received
Upvotes: 0
Views: 1014
Reputation: 23858
Your code is already pretty darn simple. You can do it in a one-liner, using this or similar in-line array rearranging code.
[x,y] = deal(mean(theArray(:,1)), mean(theArray(:,2)));
But in efficiency terms your original three liner is probably better. Splitting the array out before the mean
call will allocate more memory and costs an extra mean()
call. You could get it down to two lines without the extra memory and mean()
.
tmp = mean(theArray);
[x,y] = deal(tmp(1), tmp(2));
But that really just accomplishes the same thing as your original code, paying an additional function call at run time to save a line on paper.
Throw your code in the Matlab profiler with profile on
and see if you actually have a problem before trying to optimize. I'll bet none of these are distinguishable in practice, in which case you can stick with whatever's most readable.
Upvotes: 1
Reputation: 283634
In two lines:
x = mean(theArray(:,1));
y = mean(theArray(:,2));
Upvotes: 2