Assign a value to multiple cells in matlab

前端 未结 4 1156
旧时难觅i
旧时难觅i 2020-12-30 05:38

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         


        
相关标签:
4条回答
  • 2020-12-30 06:04

    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.

    0 讨论(0)
  • 2020-12-30 06:05

    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.

    0 讨论(0)
  • 2020-12-30 06:09

    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.

    0 讨论(0)
  • 2020-12-30 06:23

    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'
             []
             []
    
    0 讨论(0)
提交回复
热议问题