Assign a value to multiple cells in matlab

你。 提交于 2019-12-30 01:57:12

问题


I have a 1D logical vector, a cell array, and a string value I want to assign.

I tried "cell{logical} = string" but I get the following error:

The right hand side of this assignment has too few values to satisfy
the left hand side.

Do you have the solution?


回答1:


You don't actually need to use deal.

a = cell(10,1); % cell array
b = rand(1,10)>0.5; % vector with logicals
myString = 'hello'; % string

a(b) = {myString};

Looking at the last line: on the left hand side we are selecting a subset of cells from a and saying that they should all equal the cell on the right hand side, which is a cell containing a string.




回答2:


You can try this

a = cell(10,1); % cell array
b = rand(1,10)>0.5; % vector with logicals
myString = 'hello'; % string

[a{b}] = deal(myString);

It results in:

a = 

    'hello'
         []
         []
    'hello'
    'hello'
         []
    'hello'
    'hello'
         []
         []



回答3:


As H.Muster said, deal is the way to go here. The reason for the brackets is that (following H.Muster's setup) a{b} returns a comma-separated list; the brackets need to be placed around this list to concatenate it into a vector. Running help lists in Matlab might further clarify, as might the documentation on comma-separated lists

Edit: The answer provided by user2000747 seems much cleaner than using deal.




回答4:


Another solution can be

a = cell(10,1);
a([1,3]) = {[1,3,6,10]}

This may seem to be an unnecessary add, but say that you wants to assign a vector to 3 cells in an 1D cell array of length 1e8. If a logical is used, this would require creation of a logical array of size almost 100Mb.



来源:https://stackoverflow.com/questions/11456381/assign-a-value-to-multiple-cells-in-matlab

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!