MATLAB:一行的总和

发布于 2024-12-28 06:46:55 字数 434 浏览 1 评论 0原文

我正在尝试简化我的代码。我有一个 2 列数组,我想从中提取列的平均值并将它们存储为 X 和 Y。

我尝试使用以下代码:

[x y] = mean(theArray);

...但是,这会返回

??? Error using ==> mean
Too many output arguments.

现在,我已经解决了三行:

coords = mean(theArray);
x = coords(1);
y = coords(2);

我确信必须有一种更简单的方法可以在不到三行的时间内完成此操作。我的代码正在以 1000Hz 运行眼动追踪设备,我想避免任何不必要的处理...

感谢您收到的任何智慧

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

时光倒影 2025-01-04 06:46:55

分两行:

x = mean(theArray(:,1));
y = mean(theArray(:,2));

In two lines:

x = mean(theArray(:,1));
y = mean(theArray(:,2));
红墙和绿瓦 2025-01-04 06:46:55

你的代码已经非常简单了。您可以使用此或类似的内联数组重新排列代码在一行中完成此操作。

[x,y] = deal(mean(theArray(:,1)), mean(theArray(:,2)));

但就效率而言,您原来的三衬管可能更好。在 mean 调用之前拆分数组将分配更多内存并花费额外的 mean() 调用。您可以将其缩减为两行,而无需额外的内存和 mean()

tmp = mean(theArray);
[x,y] = deal(tmp(1), tmp(2));

但这实际上只是完成了与原始代码相同的事情,在运行时支付额外的函数调用以在纸上保存一行。

将您的代码放入 Matlab 分析器中,并使用 profile on 进行分析,然后在尝试优化之前查看是否确实存在问题。我敢打赌,这些在实践中都无法区分,在这种情况下,您可以坚持使用最具可读性的内容。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文