6

I want to do

myCellArray = myCcellArray{indices} 

where indices is just 0s and 1s, with same number of elements as the number of rows in myCellArray, but it doesn't work. What should I do?

3 Answers 3

12

You need to use parenthesis instead of curly braces to do the indexing.

>> arr = cell(2,2);
>> arr{1,1} = magic(4);
>> arr{1,2} = 'Hello';
>> arr{2,1} = 42;
>> arr{2,2} = pi;
>> arr

arr = 

    [4x4 double]    'Hello' 
    [        42]    [3.1416]

>> idx = logical(zeros(2,2));
>> idx(1,1) = true;
>> idx(2,2) = true;
>> arr(idx)

ans = 

    [4x4 double]
    [    3.1416]
Sign up to request clarification or add additional context in comments.

Comments

1

If you want to slice a cell-array, use parentheses. Example:

%# random cellarray of strings, and a logical indices vector
myCcellArray = cellstr(num2str((1:10)','value %02d'));   %'
indices = rand(size(myCcellArray)) > 0.5;

%# slicing
myCellArray = myCcellArray(indices)

Comments

0

What amro said is right, you should use parentheses.

But another critical thing is to use booleans not numeric 1 and 0 here.

so if you have numbers

I = [0 0 0 1 0 1]

you should use

myCellArray(I~=0)

to index it. Confusingly, a boolean array is displayed as ones and zeros in Matlab, although it is represented quite differently internally.

1 Comment

Technically, a logical array is represented internally the same as a uint8 array of ones and zeros (one byte per element, set to 0x00 or 0x01). It just has a different datatype flag, so it's interpreted differently. You can verify this by using mxGetElementSize and mxGetData to examine the two array types in a MEX function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.