Flavian Hautbois
Flavian Hautbois

Reputation: 3060

Assign a value to multiple cells in matlab

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?

Upvotes: 15

Views: 39021

Answers (4)

patrik
patrik

Reputation: 4558

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.

Upvotes: 2

zroth
zroth

Reputation: 436

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.

Upvotes: 7

user2000747
user2000747

Reputation: 246

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.

Upvotes: 23

H.Muster
H.Muster

Reputation: 9317

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

Upvotes: 14

Related Questions