【发布时间】:2012-07-12 11:19:11
【问题描述】:
我有一个一维逻辑向量、一个元胞数组和一个要分配的字符串值。
我尝试了“cell{logical} = string”,但出现以下错误:
The right hand side of this assignment has too few values to satisfy
the left hand side.
你有解决办法吗?
【问题讨论】:
我有一个一维逻辑向量、一个元胞数组和一个要分配的字符串值。
我尝试了“cell{logical} = string”,但出现以下错误:
The right hand side of this assignment has too few values to satisfy
the left hand side.
你有解决办法吗?
【问题讨论】:
您实际上不需要使用deal。
a = cell(10,1); % cell array
b = rand(1,10)>0.5; % vector with logicals
myString = 'hello'; % string
a(b) = {myString};
看最后一行:在左侧,我们从a 中选择了一个单元格子集,并说它们都应该等于右侧的单元格,这是一个包含字符串的单元格。
【讨论】:
deal 简单得多,但不知何故,我从来没有意识到需要在分配之前将右侧变成一个单元格数组。
你可以试试这个
a = cell(10,1); % cell array
b = rand(1,10)>0.5; % vector with logicals
myString = 'hello'; % string
[a{b}] = deal(myString);
结果:
a =
'hello'
[]
[]
'hello'
'hello'
[]
'hello'
'hello'
[]
[]
【讨论】:
正如 H.Muster 所说,deal 是通往这里的路。括号的原因是(按照 H.Muster 的设置)a{b} 返回一个逗号分隔的列表;需要在此列表周围放置方括号以将其连接成向量。在 Matlab 中运行 help lists 可能会进一步澄清,comma-separated lists 上的文档可能会进一步澄清
编辑: user2000747 提供的answer 似乎比使用deal 干净得多。
【讨论】:
另一种解决方案可以是
a = cell(10,1);
a([1,3]) = {[1,3,6,10]}
这似乎是不必要的添加,但假设您想将向量分配给长度为 1e8 的一维元胞数组中的 3 个元胞。如果使用逻辑,则需要创建大小接近 100Mb 的逻辑数组。
【讨论】: