如何将空数组附加到单元格数组

发布于 2025-01-17 12:15:21 字数 162 浏览 0 评论 0原文

如何将空数组附加到(非空)元胞数组?

例如,从

c={[1],[2]}

期望

c={[1],[2],[]}

连接开始将删除空数组,无论它是双精度型、字符型还是单元格型。

How do you append an empty array to a (non-empty) cell array?

For example, starting with

c={[1],[2]}

desire

c={[1],[2],[]}

Concatenation would remove the empty array whether it is double, char or cell.

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

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

发布评论

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

评论(2

晨曦慕雪 2025-01-24 12:15:21

除了@Adriaan 的回答之外,请注意,如果您小心的话,您也可以通过串联来完成此操作。

>> c = {1, 2}
c =
  1x2 cell array
    {[1]}    {[2]}
>> [c, {[]}]
ans =
  1x3 cell array
    {[1]}    {[2]}    {0x0 double}

这里的技巧是与另一个 cell 显式连接(您的问题表明您尝试过 [c, []] ,它确实什么也不做,而 [c , 1] 在操作之前自动将原始 1 转换为 {1})。

(此外,虽然在可能的情况下预分配绝对是首选,但在最新版本的 MATLAB 中,动态增长数组的损失比以前要轻得多)。

In addition to @Adriaan's answer, note that you can also do this with concatenation, if you are careful.

>> c = {1, 2}
c =
  1x2 cell array
    {[1]}    {[2]}
>> [c, {[]}]
ans =
  1x3 cell array
    {[1]}    {[2]}    {0x0 double}

The trick here is to concatenate explicitly with another cell (your question suggests you tried [c, []] which does indeed do nothing at all, whereas [c, 1] automatically converts the raw 1 into {1} before operating).

(Also, while pre-allocation is definitely preferred where possible, in recent versions of MATLAB, the penalty for growing arrays dynamically is much less severe than it used to be).

2025-01-24 12:15:21

您只需使用end+1

c={[1],[2]}
c = 
    [1]    [2]
c{end+1} = []  % end+1 "appends"
c = 
    [1]    [2]    []

MATLAB注意:附加方法通常用作在循环中大小生长数组的方法,而MATLAB中不建议将其添加。而是使用 pre-pre-Alocation> pre-pre-Alocation

You can just append it by using end+1:

c={[1],[2]}
c = 
    [1]    [2]
c{end+1} = []  % end+1 "appends"
c = 
    [1]    [2]    []

MATLAB note: appending is usually used as a way to grow an array in size within a loop, which is not recommended in MATLAB. Instead, use pre-allocation to initially apply the final size whenever possible.

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