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
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.
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
.
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.
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'
[]
[]