Clear Filters
Clear Filters

How to return the index of a cell array?

2 views (last 30 days)
Sara Al Shamsi
Sara Al Shamsi on 23 May 2016
Edited: Nut on 23 May 2016
Hi,
My code consists of 3 parts:
1- to select randomly a "cell" from a cell array. 2- return the index of the selected "cell". 3- delete the selected cell from the original cell array.
I did the first part and I got:
X =
[ 98.5004]
[4x1 double]
[5x1 double]
Then, I wanted to select a cell randomly from X and I got (example):
[4x1 double]
which is the second cell.
So, How to return its index? (manually its index is X(2)). what if I have a lot of cells? I know that "find" can be used for normal matrices but when I tried to do the same for the cell arrays, it didn't work! I read about the "cellfun" but it confused me!
last part depends on the second part! I will not be able to delete the selected cell from (X) without knowing its index! I want to delete it because when I will select randomly again from X, " I don't want to select again the same cell!

Accepted Answer

Nut
Nut on 23 May 2016
Edited: Nut on 23 May 2016
Hi,
is this example good for you?
X{1} = 1;
X{2} = [2 2 2 2];
X{3} = [3 4 5 6 7];
random_index = randi(length(X));
random_cell = X(random_index);
X{random_index} = [];
X = X(~cellfun('isempty',X));

More Answers (0)

Categories

Find more on Matrices and Arrays in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!